如何在没有top(1)的情况下通过明细表记录的计数来获取主表记录
我有一个主表(团队)和一个详细表(团队成员)。团队成员与团队有 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
I have a master table (Team) and a detail table (TeamMember). TeamMember has a FK to Team.
I need to get the Team record for the team that has the most team members. I at first had
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
I was informed that I cannot use TOP(1) in my queries. Anyone have an idea how I can do it without?
Thanks!
Team
ID, Name
TeamMember
ID, TeamID, UserID
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这个很粗糙,但很有效:
This one is crude but it works:
这让我感觉很肮脏。即使出现平局,它也会返回一个团队名称 - 如果您希望在出现平局时获得所有行,请使用
DENSE_RANK()
而不是ROW_NUMBER()
。我真的会站起来挑战“没有第一名”的规则。询问那些告诉您出于性能原因将现有查询的性能与我们提出的任何查询进行比较的人。
This makes me feel dirty. It will return a single team name even if there is a tie - if you want all rows in the event of a tie, use
DENSE_RANK()
instead ofROW_NUMBER()
.I'd really stand up and challenge the "no TOP 1" rule. Ask the person who told you it was for performance reasons to compare the performance of your existing query with any of the kludges we've come up with.
TOP 1 是最干净的方式。这是一个可能有效的非常复杂的方法:
TOP 1 is cleanest way. Here's a really convoluted way that might work: