如何在postgres中的case语句中搜索空值

时间:2016-03-23 15:04:07

标签: sql postgresql

我有一个case语句,我想处理null值。我已经做了各种测试,并认为这应该有效,但事实并非如此。

用户12345没有任何点击,但在此案例陈述中它返回20plus而不是0。有什么想法吗?

谢谢

select count(inid2), sum(clickcount) as Clicks,
CASE clickcount when clickcount=1 then '1'
when clickcount>=2 and clickcount<=5 then '2to5'
when clickcount>=6 and clickcount<=10 then '6to10'
when clickcount>=11 and clickcount<=20 then '11 to 20'
when coalesce (clickcount, 0) =0 then 'none'
else '20plus' 
END as clickbuckets
from reportingsandbox.clicktest3
where inid2 = '12345'
group by clickbuckets

1 个答案:

答案 0 :(得分:0)

您必须以这种方式编写CASE表达式:

select count(inid2), sum(clickcount) as Clicks,
       CASE  
          when clickcount=1 then '1'
          when clickcount>=2 and clickcount<=5 then '2to5'
          when clickcount>=6 and clickcount<=10 then '6to10'
          when clickcount>=11 and clickcount<=20 then '11 to 20'
          when coalesce (clickcount, 0) =0 then 'none'
          else '20plus' 
       END as clickbuckets
from reportingsandbox.clicktest3
where inid2 = '12345'
group by clickbuckets