我有一个主表(Team)和一个详细信息表(TeamMember)。 TeamMember对团队有一个FK。 我需要获得团队成员最多的团队的团队记录。我起初有
SELECT team.name
FROM team
INNER JOIN (SELECT TOP 1 COUNT(*) AS membercount,
teamID
FROM teammember
GROUP BY teamID
ORDER BY Count(*) DESC) AS team_with_most_members
ON team.id = team_with_most_members.teamID
我被告知在查询中我不能使用TOP(1)。任何人都知道如何在没有它的情况下做到这一点?
谢谢!
Team
ID, Name
TeamMember
ID, TeamID, UserID
答案 0 :(得分:3)
这个很粗糙但是有效:
SELECT t.name
FROM team AS t
JOIN teammember AS tm ON tm.teamID = t.ID
GROUP BY t.Name
HAVING COUNT(tm.id) = (SELECT MAX(members) FROM (SELECT COUNT(id) members FROM teammember GROUP BY teamid) AS sub)
答案 1 :(得分:2)
这让我觉得很脏。即使存在平局,它也会返回一个团队名称 - 如果您希望在出现平局的情况下显示所有行,请使用DENSE_RANK()
代替ROW_NUMBER()
。
SELECT t.ID, t.Name FROM
(
SELECT
TeamID, rn = ROW_NUMBER() OVER (ORDER BY c DESC)
FROM
(
SELECT TeamID, c = COUNT(*)
FROM dbo.TeamMember GROUP BY TeamID
) AS x
) AS y
INNER JOIN dbo.Team AS t
ON y.TeamID = t.ID
WHERE y.rn = 1; -- **EDIT** forgot the most important part!
我真的站起来挑战“无TOP 1”规则。询问告诉您出于性能原因的人将您现有查询的效果与我们提出的任何问题进行比较。
答案 2 :(得分:1)
TOP 1是最干净的方式。这是一种非常复杂的方式:
SELECT ID FROM (
SELECT ID, Tally, MAX(Tally) over (partition by ID) AS MaxTally
FROM (SELECT t1.ID,
COUNT(t2.ID) AS Tally
FROM @Team t1
JOIN @TeamMember t2
ON t2.TeamID = t1.ID
GROUP BY t1.ID) x
) y WHERE Tally = MaxTally