如何在 SQL 服务器 table 中获取所有具有最大值的记录

How to get all records having maximum value in a SQL Server table

我在 MigratoryBirds table SQL Server

中有以下数据
birdType
1
4
4
4
5
5
5
3

SQL 上面创建的脚本 table:

/****** Object:  Table [dbo].[migratoryBirds]    Script Date: 20-Jul-17 8:01:02 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[migratoryBirds](
    [birdType] [int] NULL
) ON [PRIMARY]

GO

我的objective是获取table中频率最高的鸟种。如果我编写一个存储过程并可以自由编写多个 SQL 查询,那么这并不困难,但我正在尝试使用单个 SQL 查询来实现它。我正在尝试查看 SQL 服务器的 Having 子句是否对我有任何帮助。

所以我写的第一个查询是:

select birdType, count(1) AS [birdCount]
from migratorybirds
group by birdType

给出以下输出

birdType birdCount
1        1
3        1
4        3
5        3

由于这是聚合的情况,所以我认为Having子句可以帮助我在这里过滤掉频率最高的记录3birdType 4 和 5 的频率最高 3.

所以,我像这样增强了我的查询:

select birdType, count(1) AS [birdCount]
from migratorybirds
group by birdType
having count(1) > Max(count(1))

给出以下错误:

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

谁能帮我实现同样的目标?

在SQL服务器中,可以使用top (1) with ties:

select top (1) with ties birdType, count(1) AS birdCount
from migratorybirds
group by birdType
order by count(1) desc;

实际上我可能会接受 Gordon 的回答,但如果您想继续使用当前的方法,您可以尝试以下方法:

WITH cte AS (
    SELECT birdType, COUNT(1) AS [birdCount]
    FROM migratorybirds
    GROUP BY birdType
)

SELECT *
FROM cte
WHERE birdCount = (SELECT MAX(birdCount) FROM cte)

如果你想以这种方式使用 MAX,你需要在 WHERE 子句中有一个实际的子查询。请注意,此解决方案需要两个查询,而 Gordon 的答案只需要一个。