[英]MySQL Case When Statement
使用GROUP BY和CASE WHEN逻辑时,如何剥离结果为空(或零)的结果?
一个假设的例子是:
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
与所有人的数据库。 这将返回3列,分别是城市,2015年所有Janes的总收入和2020年所有Janes的总收入。但是,即使没有Janes,也将返回所有城市的行。 这些城市的最后2列结果为空。 如何在查询中删除这些行,以便仅获取包含至少1个Jane的城市的行?
您需要这样的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
使用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
我在CASE
表达式中添加了ELSE 0
,以便在找不到匹配项的情况下SUM
返回0
而不是NULL
。
只要income2015
和income2020
值始终为正数,上述方法将起作用。
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
我个人比较喜欢计数非空而不是将一和零相加。 由你决定。
尝试以下-
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.