当使用GROUP和CASE逻辑时,如何用null (或零)结果剥离结果?
一个假设的例子是:
SELECT City,
SUM(case when name2015 = 'Jane' then income2015 end) income2015_total,
SUM(case when name2020 = 'Jane' then income2020 end) income2020_total
from finaldata
GROUP BY City
所有的人都有数据库。这将返回三栏:城市,2015年所有女职员的总收入,以及2020年所有女职员的总收入。然而,即使所有城市都没有简装,它也会返回一排。在最后2列中,这些城市的结果将为空。如何在查询中删除这些内容,以便只获取包含至少1 Jane的城市的行?
发布于 2015-06-23 06:32:28
使用HAVING
子句:
SELECT City,
SUM(CASE WHEN name2015 = 'Jane' THEN income2015 ELSE 0 END) income2015_total,
SUM(CASE WHEN name2020 = 'Jane' THEN income2020 ELSE 0 END) income2020_total
from finaldata
GROUP BY City
HAVING income2015_total <> 0 OR income2020_total <> 0
我在ELSE 0
表达式中添加了CASE
,以便在没有找到匹配的情况下,SUM
返回0
而不是NULL
。
如果income2015
和income2020
值总是正数,上述方法就可以工作。
Demo here
发布于 2015-06-23 06:33:51
你需要像这样的WHERE条款:
SELECT City,
SUM(case when name2015 = 'Jane' then income2015 end) income2015_total,
SUM(case when name2020 = 'Jane' then income2020 end) income2020_total
from finaldata
WHERE name2015 = 'Jane' OR name2020 = 'Jane'
GROUP BY City
发布于 2015-06-23 06:32:44
SELECT City,
SUM(case when name2015 = 'Jane' then income2015 end) income2015_total,
SUM(case when name2020 = 'Jane' then income2020 end) income2020_total
from finaldata
GROUP BY City
HAVING COUNT(case when 'Jane' in (name2015, name2020) then 1 else null end) > 0
我个人更喜欢计算非零数,而不是求和1和零。你说了算。
https://stackoverflow.com/questions/30995318
复制相似问题