SQL从CASE语句返回多个值

时间:2023-02-03 02:02:50

How do I rewrite this SQL statement to do what I need?

如何重写此SQL语句以执行我需要的操作?

 SELECT * FROM TABLE 
    WHERE COLUMN_NAME_1 IN (CASE 
        WHEN COLUMN_NAME_2 = 'X' THEN 'A' 
        WHEN COLUMN_NAME_2 = 'Y' THEN 'B', 'C' END)

Obviously I can't return multiple values from a CASE clause... so how else could I write this? I am pretty sure I am slow today because this seems so easy ....

显然我不能从CASE子句中返回多个值...那么我怎么能写这个呢?我很确定今天我很慢,因为这看起来很容易....

1 个解决方案

#1


3  

 SELECT * FROM Table WHERE
    (COLUMN_NAME_2 = 'X' AND COLUMN_NAME_1 = 'A') OR
    (COLUMN_NAME_2 = 'Y' AND COLUMN_NAME_1 IN ('B', 'C'))

or

 SELECT * FROM Table WHERE COLUMN_NAME_2 = 'X' AND COLUMN_NAME_1 = 'A'
 UNION ALL
 SELECT * FROM Table WHERE COLUMN_NAME_2 = 'Y' AND COLUMN_NAME_1 IN ('B', 'C')

This presumes that you only want results with X or Y in COLUMN_NAME_2. If you want other rows it's not possible to tell which ones from your original SQL.

这假设您只需要在COLUMN_NAME_2中使用X或Y的结果。如果您想要其他行,则无法分辨原始SQL中的哪些行。

#1


3  

 SELECT * FROM Table WHERE
    (COLUMN_NAME_2 = 'X' AND COLUMN_NAME_1 = 'A') OR
    (COLUMN_NAME_2 = 'Y' AND COLUMN_NAME_1 IN ('B', 'C'))

or

 SELECT * FROM Table WHERE COLUMN_NAME_2 = 'X' AND COLUMN_NAME_1 = 'A'
 UNION ALL
 SELECT * FROM Table WHERE COLUMN_NAME_2 = 'Y' AND COLUMN_NAME_1 IN ('B', 'C')

This presumes that you only want results with X or Y in COLUMN_NAME_2. If you want other rows it's not possible to tell which ones from your original SQL.

这假设您只需要在COLUMN_NAME_2中使用X或Y的结果。如果您想要其他行,则无法分辨原始SQL中的哪些行。