SQL check if numrical value is 0 for a field where id is=333 - sql

inside an SQL SELECT CASE STATEMENT how would i check if the a value for some coulmn in sometable is equal to 0 where the id is equal to something?

select
case
when (select column_name from sometable where id = #id) = 0 then
else
end

select
case when( select column from table where id=333)=0 then "your condition"
else
end

My interpretation of your question:
SQL check if numerical value is 0 for a field (Field1) [only] when id is=333
[If id is not 333, don't need to check]
SELECT CASE WHEN isnull(id,0) <> 333 OR Field1=0 THEN 1 ELSE 0 END
,other1, other2
FROM tbl

Related

SQL AS query results in duplicate column

I have a SQL query like so
SELECT
name,
CASE WHEN (new_value=2) THEN 0 END as out,
CASE WHEN (previous_value=2) THEN 1 END as out
FROM my_table;
This results in duplicate columns:
name out out
foo 1 null
bar null 1
instead of
name out
foo 1
bar 0
How do I fix this?
You want one case expression with two conditions:
SELECT name,
(CASE WHEN new_value = 2 THEN 0
WHEN previous_value = 2 THEN 1
END) as out
FROM my_table;
Consider:
SELECT
name,
CASE
WHEN new_value = 2 THEN 0
WHEN previous_value = 2 THEN 1
END as out
FROM my_table;
In your query, each case expression generates one column in the resulset. You want only one, with two branches (denoted by when ... then ...)
You are getting null output, so you need to add else on this.
select name,
case
when new_value = 2 then 0
when previous_value = 2 then 1
else 0 end as out
from my_table;

How to check if all rows validate a predicate

I've a table in my database for which I need to check if all rows have one field not null.
If there are no row or if there is at least 1 row with the field null => true
If there are rows and they are all with the field not null => False
Is there a way to do this in on simple query? Or I need to check if my table is empty first then if it's not check if I've a row with the field value empty ?
This will count how many NULL values you have in a field;
SELECT
SUM(CASE WHEN FieldName IS NULL THEN 1 ELSE 0 END) NullValues
FROM TableName
Will return 0 if there are no NULL values, and will return the number of NULLS if there are any present.
If you actually want to return a value as 'True' or 'False' then do this;
SELECT CASE
WHEN a.NullValues > 0
THEN 'True'
ELSE 'False'
END CheckField
FROM (
SELECT
SUM(CASE WHEN FieldName IS NULL
THEN 1
ELSE 0
END) NullValues
FROM TableName
) a
Use count(*) and count(field) and compare the two:
select
case when count(*) > 0 and count(*) = count(field) then 1 -- not empty and no nulls
else 0 end as isgood
from mytable;
Oracle SQL has no boolean data type , so I use 1 for true and 0 for false. You can replace this with whatever you like (e.g. 'true' instead of 1 and 'false' instead of 0).
As to turning this into a predicate (correlated to a main query), you'd use something along the lines of:
select ...
from main
where exists
(
select 1
from mytable
where mytable.colx = main.coly
having count(*) > 0 and count(*) = count(field)
);
You can do this with aggregation. However, it is difficult to understand what you are asking for. If you want to check that a field has no NULL values, you can do:
select (case when count(*) > 0 then 1 else 0 end) as HasNullValues
from t
where field is null;
Alternate way I found using max with putting null first:
select case when
max(field) keep (dense_rank first order by datfin desc nulls first) is null then 1
else 0 end as flag
from MYTABLE;

SQL - Command to get Id's with unique flags from multiple flags

ID Risk_1 Risk_2 Risk_3 Risk_4
XYZ Yes Yes Yes
ABC Yes
PQR Yes Yes
As you can see from the above table There are IDs that have multiple risks associated with them. I want to get an output of IDs where only one risk is associated with them.
In the case above I want all IDs which have only risk_1 so the result should be ABC.
How can I get this done using SQL?
Assuming that Risks are nullable.
SELECT ID
FROM tableName
WHERE CASE WHEN Risk_1 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN Risk_2 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN Risk_3 IS NOT NULL THEN 1 ELSE 0 END +
CASE WHEN Risk_4 IS NOT NULL THEN 1 ELSE 0 END = 1
SQLFiddle Demo
if however they are empty string,
SELECT ID
FROM tableName
WHERE CASE WHEN Risk_1 <> '' THEN 1 ELSE 0 END +
CASE WHEN Risk_2 <> '' THEN 1 ELSE 0 END +
CASE WHEN Risk_3 <> '' THEN 1 ELSE 0 END +
CASE WHEN Risk_4 <> '' THEN 1 ELSE 0 END = 1
SQLFiddle Demo
That will work with NULLs, empty strings, or values other than Yes (e.g. No)
SELECT ID
FROM Table1
WHERE COALESCE(Risk_1, 'No') = 'Yes' AND
COALESCE(Risk_2, 'No') <> 'Yes' AND
COALESCE(Risk_3, 'No') <> 'Yes' AND
COALESCE(Risk_4, 'No') <> 'Yes'
sqlfiddle
If the value of risks are only 'Yes' then below query will work
select ID from table where risk1||risk2||risk3||risk4='Yes'
If the value of risks are only 'Yes' and the empty risks have spaces instead of nulls then below query will work
select ID from table where replace(risk1||risk2||risk3||risk4,' ','')='Yes'
If you altered your schema so your table had columns ID and risk_type with a row for each risk type, you could have a query like this:
SELECT ID
FROM Table1
GROUP BY ID
HAVING COUNT(*) = 1
SQLFiddle
re-edit: modified to no longer specify which one risk type they have

SQL CASE SUBQUERY COUNT

I have table with 2 col :
UID NAME
-----------
111 AAA
222 BBB
Customer will enter the name and I have to retrieve UID with respective value. If name won't present in the rows, it has to retrieve 000, not like no rows.
I am trying to write query like this:
SELECT
CASE UID
WHEN Count(*) = 0 THEN '000'
ELSE UID
END
FROM table1
WHERE NAME ='XXX'
Please help me in this regard. Thanks in advance...
If UID is an integer, then you need to take casts into account:
select coalesce(cast(max(uid) as char(3)), '000')
from table1
where name = 'XXX'
The cast is intended to be to the type of UID, which seems to be char(3) in your example.
When there are no matching rows, then the max() function returns NULL. The coalesce() turns this into the value you are looking for.
try this
select case
when max(id) is null then
0
else
max(id)
end
from table1
where name = 'b'
You have error in case
SELECT case when count(UID) = 0 THEN '000' ELSE UID end FROM table1 where name = 'XXX'
sqlfiddle :http://www.sqlfiddle.com/#!2/257ea/1

SQL: Alias Column Name for Use in CASE Statement

Is it possible to alias a column name and then use that in a CASE statement? For example,
SELECT col1 as a, CASE WHEN a = 'test' THEN 'yes' END as value FROM table;
I am trying to alias the column because actually my CASE statement would be generated programmatically, and I want the column that the case statement uses to be specified in the SQL instead of having to pass another parameter to the program.
This:
SELECT col1 as a,
CASE WHEN a = 'test' THEN 'yes' END as value
FROM table;
...will not work. This will:
SELECT CASE WHEN a = 'test' THEN 'yes' END as value
FROM (SELECT col1 AS a
FROM TABLE)
Why you wouldn't use:
SELECT t.col1 as a,
CASE WHEN t.col1 = 'test' THEN 'yes' END as value
FROM TABLE t;
...I don't know.
I think that MySql and MsSql won't allow this because they will try to find all columns in the CASE clause as columns of the tables in the WHERE clause.
I don't know what DBMS you are talking about, but I guess you could do something like this in any DBMS:
SELECT *, CASE WHEN a = 'test' THEN 'yes' END as value FROM (
SELECT col1 as a FROM table
) q
#OMG Ponies - One of my reasons of not using the following code
SELECT t.col1 as a,
CASE WHEN t.col1 = 'test' THEN 'yes' END as value
FROM TABLE t;
can be that the t.col1 is not an actual column in the table. For example, it can be a value from a XML column like
Select XMLColumnName.value('(XMLPathOfTag)[1]', 'varchar(max)')
as XMLTagAlias from Table
It should work. Try this
Select * from
(select col1, col2, case when 1=1 then 'ok' end as alias_col
from table)
as tmp_table
order by
case when #sortBy = 1 then tmp_table.alias_col end asc
I use CTEs to help compose complicated SQL queries but not all RDBMS' support them. You can think of them as query scope views. Here is an example in t-sql on SQL server.
With localView1 as (
select c1,
c2,
c3,
c4,
((c2-c4)*(3))+c1 as "complex"
from realTable1)
, localView2 as (
select case complex WHEN 0 THEN 'Empty' ELSE 'Not Empty' end as formula1,
complex * complex as formula2
from localView1)
select *
from localView2
Nor in MsSql
SELECT col1 AS o, e = CASE WHEN o < GETDATE() THEN o ELSE GETDATE() END
FROM Table1
Returns:
Msg 207, Level 16, State 3, Line 1
Invalid column name 'o'.
Msg 207, Level 16, State 3, Line 1
Invalid column name 'o'.
However if I change to CASE WHEN col1... THEN col1 it works
If you write only equal condition just:
Select Case columns1 When 0 then 'Value1'
when 1 then 'Value2' else 'Unknown' End
If you want to write greater , Less then or equal you must do like this:
Select Case When [ColumnsName] >0 then 'value1' When [ColumnsName]=0 Or [ColumnsName]<0 then
'value2'
Else
'Unkownvalue' End
From tablename
Thanks
Mr.Buntha Khin
SELECT
a AS [blabla a],
b [blabla b],
CASE c
WHEN 1 THEN 'aaa'
WHEN 2 THEN 'bbb'
ELSE 'unknown'
END AS [my alias],
d AS [blabla d]
FROM mytable
Not in MySQL. I tried it and I get the following error:
ERROR 1054 (42S22): Unknown column 'a' in 'field list'
In MySql, alice name may not work, therefore put the original column name in the CASE statement
SELECT col1 as a, CASE WHEN col1 = 'test' THEN 'yes' END as value FROM table;
Sometimes above query also may return error, I don`t know why (I faced this problem in my two different development machine). Therefore put the CASE statement into the "(...)" as below:
SELECT col1 as a, (CASE WHEN col1 = 'test' THEN 'yes' END) as value FROM table;
Yes, you just need to add a parenthesis :
SELECT col1 as a, (CASE WHEN a = 'test' THEN 'yes' END) as value FROM table;
make it so easy.
select columnnameshow = (CASE tipoventa
when 'CONTADO' then 'contadito'
when 'CREDITO' then 'cred'
else 'no result'
end) from Promocion.Promocion