问题描述
我的表格由3列组成; id,state,carColour和超过100万行。 我想返回所有黑色汽车比白色汽车多的州。
我尝试过:
SELECT state
FROM table
WHERE state IN (SELECT state
FROM table
WHERE COUNT(carColour = 'Black') > COUNT(carColour = 'White'))
GROUP BY state
但是显然where语句中的count()不起作用...我该如何解决?
解决方法
不需要子查询。您可以使用条件聚集在having
子句中进行过滤:
select state
from mytable
group by state
having sum(case when carColour = 'Black' then 1 else 0 end)
> sum(case when carColour = 'White' then 1 else 0 end)
这使用标准case
语法,几乎所有地方都支持该语法。一些数据库具有快捷方式。例如,Postgres和SQLite支持filter
子句:
having count(*) filter(where carColour = 'Black')
> count(*) filter(where carColour = 'White')