我正在运行PostgreSQL。我有一个名为foo
的表。其内容是:
city|number
'oo'|12
'ss'|11
'ss'|23
'oo'|11
'pp'|21
如果我运行select count(city) from foo group by city having number<21
这样的查询,我会得到
city|number
'oo'|2
'ss'|2
但我希望结果能够考虑city
这样的所有可能情况:
city|number
'oo'|2
'ss'|2
'pp'|0
查询应该如何?
答案 0 :(得分:1)
SELECT city, count(NULLIF(number < 21, false)) FROM cities GROUP BY city
应该给你想要的结果。
答案 1 :(得分:0)
想想我第一次误读了这个问题,但试试这个:
select f1.city,count(*) from foo f1
where f1.city in (select f2.city from foo f2 where f2.number < 21)
group by f1.city
union
select f3.city,0 from foo f3
where not exists (select * from foo f4 where f3.city=f4.city and f4.number < 21)
group by f3.city
联合分割查询,以便前半部分将识别哪些城市的条目<21,然后计算这些城市的出现次数。
下半部分识别没有条目<21的城市,然后计算它们。
答案 2 :(得分:0)
这可以通过左连接来解决:
select f1.city, count(f2.number) as total from foo as f1
left join foo as f2
on f1.cityId = f2.cityId and f1.number < 21
group by f1.city
这是一个有效的example
PS:您的示例是错误的,因为ss的值应为1,而不是2:
YOUR EXAMPLE WHAT I THINK YOU REALLY WANT
city|number city|number
'oo'|2 'oo'|2
'ss'|2 'ss'|1
'pp'|0 'pp'|0
希望这有帮助。