我有以下sql语句:
select val, count(*) as tally from sometable group by val order by tally desc
生成以下(示例)表:
val | tally
----+-------
4 | 20
5 | 10
6 | 5
7 | 3
8 | 2
现在,我想只显示tally > 5
所在的行,结果将是:
val | tally
----+-------
4 | 20
5 | 10
我尝试了这个陈述,但它没有用(它说“理货”未知):
select val, count(*) as tally from sometable where tally > 5 group by val order by tally desc
答案 0 :(得分:5)
尝试HAVING(more information):
select val, count(*) as tally from sometable group by val having tally > 5 order by tally desc
答案 1 :(得分:0)
您可以采取两种方法:
1:使用HAVING
。这意味着将根据HAVING
子句筛选查询结果,并且只会返回一些原始结果行:
SELECT val, COUNT( * ) AS tally
FROM sometable
GROUP BY val
ORDER BY tally DESC
HAVING tally > 5
2:使用子选择。这可能会给你带来更好的性能(我不是sql guru,所以我不能自信地说):
SELECT val, tally
FROM (SELECT val, COUNT( * ) AS tally
FROM sometable
GROUP BY val
ORDER BY tally DESC)
temp
WHERE tally >1