SQL查询使用CASE选择某些行

时间:2017-10-16 23:19:48

标签: mysql sql

我有一张表格,如下所示

+++++++++++++++++++++++++
colA | colB | colC | colD
+++++++++++++++++++++++++
1 | female | ... | ...
2 | male   | ... | ...
3 |        | ... | ...
4 | select | ... | ...
5 | dfd    | ... | ...
+++++++++++++++++++++++++

我想在colB中选择“女性”或“男性”的所有行,并在colB中选择空或“选择”值的行,但是要将其重命名为“未知”。结果表应为:

+++++++++++++++++++++++++
colA | colB | colC | colD
+++++++++++++++++++++++++
1 | female | ... | ...
2 | male   | ... | ...
3 | unknown| ... | ...
4 | uknown | ... | ...
+++++++++++++++++++++++++

我的疑问是:

SELECT colA, colB, colC, colD FROM table 
where (colB in ('female','male') and 
        case when colB = '' then 'unknown'
             when colB = 'select' then 'unknown' end)

2 个答案:

答案 0 :(得分:2)

所以你想要有四个值的行,但你想以不同的方式呈现两个案例。

更改值的显示应在选择列表中完成。

SELECT colA, 
  CASE WHEN colB IN ('','select') THEN 'unknown' ELSE colB END AS colB,      
  colC, colD 
FROM table
WHERE colB IN ('','select','female','male');

答案 1 :(得分:2)

您似乎想要:

SELECT colA,
       (CASE WHEN colB IN ('female', 'male') THEN colb ELSE 'unknown' END) as colB,
       colC, colD
FROM table 
WHERE colB in ('female', 'male', '') OR colB IS NULL;