错误:聚合可能不会出现在WHERE子句中

时间:2012-11-28 11:06:53

标签: sql sql-server

我正在尝试获取列的最大值:

select * from
( select col1, count(*) as cnt from talbe1
group by col1
) dt
where cnt = max(cnt)

我试图获得确切的价值,但它的工作原理如下:

where cnt = 5   

where cnt > 3  

那可以,第一个查询出了什么问题?

编辑:我放在那里的数字(5,3)是完全随机的,我想获得最大数量的cnt。

4 个答案:

答案 0 :(得分:2)

汇总条款必须放在HAVING部分。但是,这不适用于您的查询。你可能想做的是:

select top 1 col1, count(*) as cnt 
from talbe1
group by col1
order by count(*) desc

答案 1 :(得分:2)

您可以使用HAVING子句执行此操作。例如,如果您想获得cnt=3条记录

Select col1, count(*) as cnt from talbe1
Group by col1
Having count(*)=3

如果您想获得MAX(cnt)

Select Top(1) col1, count(*) as cnt from talbe1
Group by col1
Order by cnt desc

答案 2 :(得分:1)

我找到了解决方案,
这很简单:(我应该更专注)

select max(cnt) from
( select Fld301, count(*) as cnt from TbC3
group by Fld301
) dt

答案 3 :(得分:1)

这个查询怎么样:

select * from
(
    select 
        col1, 
        count(*) as cnt, 
        RANK() OVER(ORDER BY count(*) DESC) AS ran 
    from talbe1 
    group by col1
) dt
where ran=1