我正在使用DB2并尝试限制使用group by的查询仅包含大于某个阈值的计数但无法通过语法错误
select val, count(*) as c from sample_table
where c > 20
group by val;
它不喜欢我引用c并在where子句中使用它的事实。
我如何实现这样的目标?
答案 0 :(得分:3)
你可以这样做:
select *
from (
select val, count(*) as c
from sample_table
group by val
)
where c > 20
但要做得更好:
select val, count(*) as c
from sample_table
group by val
having count(*) > 20
答案 1 :(得分:1)
您可以使用HAVING
:
select val, count(*) as c
from sample_table
group by val;
having count(*)> 20
答案 2 :(得分:0)
你不能在where子句中使用聚合函数,所以你必须使用HAVING。
select val, count(*) as c
from sample_table
group by val
Having c>20;