简体   繁体   中英

SQL Server WHEN and subqueries

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
        );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM