2011-11-16 154 views
2

我有一個包含名爲MySubId的列的行。此列中的值可以重複。我想查找MySubId值和出現最多的MySubId值的行數。SQL Server GROUP BY困境

我有以下查詢:

SELECT MySubId, COUNT(MySubId) AS MySubIdCount 
FROM MyTable 
GROUP BY MySubId 
HAVING COUNT(MySubId)=MAX(COUNT(MySubId)) 

但我得到的錯誤:

Msg 130, Level 15, State 1, Line 4 Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

是沒可能用一個簡單的查詢來做到這一點?在使用HAVING條款之前,是否必須嵌入子查詢來計算MAX?

更新:

我看到很多anwers過濾結果通過TOP 1設定的,所以我是假設沒有辦法使用MAX功能來過濾這個查詢只是最大出現MySubId值?

回答

6
select top 1 with ties MySubId, Count(MySubId) as MySubIdCount 
from MyTable 
group by MuSubId 
order by 2 desc 
+0

+1考慮到多個MySubIds共享相同的最大數量的可能性。 –

+0

+1(出於同樣的原因) –

+1

+1不知何故,我從來不知道'帶領帶'存在,我一直這樣做是一種艱難的方式永遠... –

1
select top 1 MySubId, Count(MySubId) 
from MyTable 
group by MySubId 
order by count(MySubId) DESC 
0

這僅僅是一個供參考,因爲我相信這將是海報

下一個合乎邏輯的步驟。如果要刪除所有重複開始與最新的...

DECLARE @ROWCOUNT INT 
SET @ROWCOUNT = 1 

WHILE @ROWCOUNT > 0 
BEGIN 
    DELETE 
    FROM MyTable 
    WHERE ID IN 
    (
     SELECT MAX(ID) 
     FROM MyTable 
     GROUP By MySubID 
     HAVING COUNT(1) > 1 
    ) 
    SET @ROWCOUNT = @@ROWCOUNT 
END 
+0

這只是一個FYI – SQLMason

0
DECLARE @MyTable TABLE (
    MySubId INT 
) 

INSERT INTO @MyTable (MySubId) VALUES (1) 
INSERT INTO @MyTable (MySubId) VALUES (1) 
INSERT INTO @MyTable (MySubId) VALUES (1) 
INSERT INTO @MyTable (MySubId) VALUES (2) 
INSERT INTO @MyTable (MySubId) VALUES (2) 
INSERT INTO @MyTable (MySubId) VALUES (2) 
INSERT INTO @MyTable (MySubId) VALUES (2) 
INSERT INTO @MyTable (MySubId) VALUES (3) 
INSERT INTO @MyTable (MySubId) VALUES (3) 
INSERT INTO @MyTable (MySubId) VALUES (3) 
INSERT INTO @MyTable (MySubId) VALUES (3) 

;WITH Counts_CTE (MySubId, MySubIdCount, RowNumber) 
AS 
(
    SELECT 
     MySubId, 
     COUNT(MySubId) AS MySubIdCount, 
     DENSE_RANK() OVER (ORDER BY COUNT(MySubId) DESC) AS RowNumber 
    FROM @MyTable 
    GROUP BY MySubId 
) 
SELECT * 
FROM Counts_CTE 
WHERE RowNumber = 1