2012-11-28 37 views
0

我試圖讓列的Max在:錯誤:聚合不應出現在WHERE子句

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。

回答

2

彙總條款必須進入HAVING部分。但是,這不適用於您的查詢。你可能想要做的是:

select top 1 col1, count(*) as cnt 
from talbe1 
group by col1 
order by count(*) desc 
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 
+0

這只是返回3計數不是MAX? – Star

+0

@明星我認爲這是他正在嘗試按照OP – Kaf

+0

得到的不是我是OP,對不起,也許我沒有很好地解決我的問題, 反正謝謝。 – Star

1

我找到了解決辦法,
這是很簡單的:(我應該集中更多)

select max(cnt) from 
(select Fld301, count(*) as cnt from TbC3 
group by Fld301 
) dt 
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 
相關問題