SQL Server WHEN and subqueries - sql

I needed help with a question and what would be the most clean way of doing this in SQL SERVER.
I am basically writing a query that checks if a customer number is inside another subquery then it should return the servicename for that customer number. This is my attempt and it is not working.
Do you guys have any suggestions?
CASE WHEN aa.cust_no in (SELECT Cust_no FROM #Tabl1) THEN (SELECT ServiceName FROM #Tabl1) END AS Target

I get what you're trying to do, but you syntax needs to be changed. You can try a LEFT JOIN.
This query will give you an idea of what your statement should look like
Select tabl1.ServiceName Target
From SomeTable aa
Left Join #Tabl1 tabl1
On aa.cust_no = tabl1.Cust_no
If you want to put something else if a match is not found in #Tabl1, then you will need to use a WHEN, or a COALESCE.
When tabl1.ServiceName Is NOT NULL Then tabl1.ServiceName Else 'Unknown Target' End
OR
Coalesce (tabl1.ServiceName, 'Unknown Target') Target

instead of case expression try select ServiceName in this way:
SELECT
(SELECT TOP 1 ServiceName FROM #Tabl1 where Cust_no = aa.cust_no) AS Target
FROM ...

I think ure missing one parameter look
CASE Expression
WHEN Value1 THEN Result1
WHEN Value2 THEN Result2
ELSE Alternative
END
I hope this could help...
CASE aa.cust_no
WHEN (SELECT Cust_no FROM #Tabl1 WHERE #Tabl1.cust_no) THEN (SELECT ServiceName FROM #Tabl1 WHERE #Tabl1.cust_no)
ELSE 'NO ServiceName'
END AS Target

I believe this should get what you are looking for.
SELECT serviceName
FROM table_A
WHERE cust_no IN (
SELECT cust_no
FROM table_B
);

Related

Anyway to use IN operator in the SELECT statement? If not, why?

This may come off as a feature request more than anything, but it would be nice if SQL allowed use of the IN operator in a select statement such as the one below. I want to create new_variable intable1based on the ID variable in table2, hence the case statement.
select ID,
case when ID in (select ID
from table2)
then 1
else 0
end as new_variable
from table1
I understand that SQL will give me an error if I run this, but why is that the case? It doesn't seem obvious to me why SQL developers couldn't enable the IN operator to be used outside of the WHERE clause.
Side note: I'm currently using a left join to avoid this issue, so I am not hung up on this.
select ID,
case when ifnull(b.ID, 0) = 0 then 0
else 1
end as variable_name
from table1
left join(select ID from table2) as b
on a.ID = b.ID
SQL definitely supports this:
select ID,
(case when ID in (select ID from table2)
then 1 else 0
end) as new_variable
from table1
Note that there is a comma after id.
This is standard SQL. If your database doesn't support it, it is a feature request (and one that all or almost all databases support).

How to check if a field exists in SQL subquery?

I have to do a lot of queries with this kind of logic:
Check if a table contains a record for a patient
If it does return then 'Yes'
Else return 'No'
Now, I want to create a procedure that will do this, so I tried to create a function that will do the above, but ended up in dynamic queries which is not possible in functions.
Is it possible to achieve this? How can I go about this?
PS:
Maybe something like:
select
(IF EXISTS(SELECT * FROM Dtl_Patient WHERE Pk = 3990 select 'Yes' else select 'No')) as output from dtl_AllPatient;
Try CASE
SELECT
CASE WHEN EXISTS (SELECT PatientID FROM Table2 T2 WHERE T2.PatientID =T1.PatientID)
THEN 'YES' ELSE 'NO' END AS PatientExists
FROM
Table1 T1
EDIT
SELECT
CASE WHEN EXISTS (SELECT Pk FROM Dtl_Patient WHERE Pk = 3990) THEN 'YES' ELSE 'NO' END AS PatientExists
FROM dtl_AllPatient
check this EXISTS Condition
The SQL EXISTS condition is considered "to be met" if the subquery returns at least one row.

How to summarize SQL table to return value conditionally

I have a table with several rows, and several columns. It looks like this:
Name Description
X PASS
X PASS
X FAIL
I want it to return only one row. If all of them are PASS, return PASS.
If one or more of them are FAIL, then return FAIL.
What's the best way to go about achieving this in SQL Server 2008?
EDIT: The values in the name column will always be the same.
Depending on the database indexes, and assuming you want one row returned per unique name, I would look at the performance of
select
name,
min([description]) as description
from
tableA
group by
name
compared to the other solutions
SELECT TOP 1 CASE Description WHEN 'FAIL' THEN 'FAIL' ELSE 'PASS' END
FROM DaTable
ORDER BY Description
OP: Is it possible that the table is empty? In that case this query won't return any rows, obviously.
EDIT
According to aquinas's comment I created a modified query without ordering:
SELECT CASE COUNT(Description) WHEN 0 THEN 'FAIL' ELSE 'PASS' END
FROM DaTable
WHERE Description = 'FAIL'
This query will return PASS if DaTable is empty.
This is the simplest solution you will find:
SELECT MIN(Description) FROM tbl
If there's at least one FAIL, then our result column will contain FAIL, otherwise, it will contain PASS.
You can use EXISTS to get the existance of a row containing "FAIL".
You could also try something like:
SELECT TOP 1 COALESCE(tFail.Description,t.Description)
FROM myTable AS t
LEFT JOIN myTable AS tFail ON tFail.Name = t.Name AND tFail.Description = 'FAIL'
WHERE t.Name = 'x'
Here is the query:
--DROP TABLE result
CREATE TABLE result(Name varchar(10),Description varchar(20))
--select * from result
INSERT INTO result
VALUES('X','PASS'),('X','PASS'),('X','FAIL')
;WITH CTE(descp,cnt) as (SELECT [description],COUNT(*) as cnt FROM result group by [description])
SELECT CASE WHEN COUNT(*) > 1 then 'FAIL' when COUNT(*)=1 then MAX(descp) else 'PASS' END FROM CTE

How to return multiple values using case statement in oracle

I want to return multiple values from a query in oracle. For ex:
select count(*)
from tablename a
where asofdate='10-nov-2009'
and a.FILENAME in (case
when 1 = 1 then (select distinct filename from tablename
where asofdate='10-nov-2009' and isin is null)
else null
end);
I am getting error: ora 01427 single row subquery returns more than one row
Please advice.
Thanks, Deepak
A CASE statement cannot return more than one value, it is a function working on one value.
It is not required for your statement, this statement should work:
select count(*)
from tablename a
where asofdate='10-nov-2009'
and a.FILENAME in (select distinct filename
from tablename
where asofdate='10-nov-2009'
and isin is null);
Maybe you have another usage scenario in mind? Something like this:
Select *
From aTable
Where in CASE
WHEN Then
WHEN Then
ELSE END
Then using CASE may not be the right scenario. Maybe this helps you in the right direction:
Select *
From aTable
Where <Case1> and column1 in <Subselect1>
Or <Case2> and column1 in <Subselect2>
OR Not (<Case1> Or <Case2>) and column1 in <Subselect3>
But this will probably be quite some work for the optimizer ...
The distinct in your Case statement is attempting to return multiple values when only one is allowed, and your SELECT statement will only return one value in one row currently. If you're trying to get the count of each filename, do
SELECT FileName, Count(*)
FROM tablename
WHERE asofdate='10-nov-2009' and isin is null
GROUP BY FileName
Run this query:
select distinct filename from tablename
where asofdate='10-nov-2009' and isin is null
You'll see that it returns more than a single row which causes the ORA-01427.
For all I can tell, you're looking for something like:
select a.filename, count(*)
from tablename a
where a.asofdate = '10-nov-2009'
and exists (
select *
from tablename b
where b.isin is null
and a.asofdate = '10-nov-2009'
and a.filename = b.filename
)
group by a.filename
This would find the count of filenames for a day, for which there exists at least one row where isin is null.
If you edit your question and add an explanation of what you're looking for, you might get better answers.

Proper sql query in MySQL

I have table like this:
Name Result
T1 fail
T2 pass
T3 pass
T2 fail
T4 fail
T1 pass
T4 fail
Now, I want to get a results like this:
Name Result
T1 pass
T2 pass
T3 pass
T4 fail
I tried using query like this, but it does not work.
select (case when Result = "pass" then "pass" else "fail" end) as Final_verdict,
Name from table_1 group by Name
Can anyone please tell me what am I missing?
EDIT
Try the following:
SELECT Name, MAX(Result) As Result
FROM table_1
GROUP BY Name
This should return pass whenever there is one passed record for a row, as pass is lexicographically after fail.
Use else instead of the second then, and use end at the end of the case.
You might also have to use single quotes.
select (case when Result = 'pass' then 'pass' then 'fail' end) as Final_verdict,
Name
from table_1
What do you expect to happen when the same name has different results?
Not the most pretty way, but depending on what you want to happen:
You want fail when there is any fail:
select name, min(result) from table_ 1 group by name;
You want pass if there is any pass:
select name, max(result) from table_ 1 group by name;
Or did you only want the last result for each Name in the table?