SQL Server GROUP BY进退两难

时间:2011-11-16 20:03:07

标签: sql sql-server-2008 tsql sql-server-2008-r2

我有一个包含名为MySubId的列的行的表。此列中的值可以重复。我想找到MySubId值以及出现次数最多的MySubId值的行数。

我有以下查询:

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

但我收到错误:

  

消息130,级别15,状态1,行4无法执行聚合   对包含聚合或子查询的表达式起作用。

使用简单查询无法做到这一点吗?在HAVING子句中使用它之前,我必须嵌入一个子查询来计算MAX吗?

更新

我看到很多anwers使用TOP 1过滤结果集,所以我假设没有办法使用MAX函数将此查询过滤到最大值{{ {1}}值?

4 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

这只是一个FYI,因为我相信这将是海报的下一个合乎逻辑的步骤

如果要删除所有以最新...

开头的重复项
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

答案 3 :(得分: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