我试图从表格中选择一个值,如下例所示:
user id_1 id_2 id_3
-----------------------
a 1 NULL 3
b 1 NULL NULL
c NULL NULL 3
d NULL 2 NULL
我使用以下支点来得出上述结果:
select user,
max(case when id = 1 then id end) as id_1,
max(case when id = 2 then id end) as id_2,
max(case when id = 3 then id end) as id_3
from table t
group by user
order by user;
我想将Null更改为零以获得以下结果:
user id_1 id_2 id_3
-----------------------
a 1 0 3
b 1 0 0
c 0 0 3
d 0 2 0
我使用了COALESCE
,如下所示:
select user,
max(case when id = 1 then COALESCE(id,0) end) as id_1,
max(case when id = 2 then COALESCE(id,0) end) as id_2,
max(case when id = 3 then COALESCE(id,0) end) as id_3
from table t
group by user
order by user;
但它没有用,有什么建议吗?
答案 0 :(得分:3)
当WHEN不满足时,每个CASE语句都评估为NULL。当所有值都为NULL时,MAX()返回NULL。如果您只想获得0而不是NULL,请在每个else 0
之前添加end
。
select user,
max(case when id = 1 then id else 0 end) as id_1,
max(case when id = 2 then id else 0 end) as id_2,
max(case when id = 3 then id else 0 end) as id_3
from table t
group by user
order by user;
答案 1 :(得分:0)
Mugos解决方案可能是最好的方法,所以这只是为了表明还有其他方法可以做到这一点。在你查询COALESCE never(假设id不能为null)有任何影响,因为如果case评估为true - > id(我假设不能为null),如果case计算结果为false,则不应用COALESCE。正如Mugo演示的那样,您可以通过在案例中添加其他内容来解决此问题。另一种方法是在CASE之外应用COALESCE:
select user,
COALESCE(max(case when id = 1 then id end),0) as id_1,
...
FWIW,CASE的另一种变体有点短:
select user,
COALESCE(max(case id when 1 then id end),0) as id_1,
...