最多2个基于其他列的常用值

时间:2012-12-26 22:35:03

标签: sql sql-server

我有这张桌子:

Team | Player
Barca | Messi
Chelsea | Lampard
Barca | Messi
Barca | Messi
Chelsea | Lampard
Chelsea | Drogba
Barca | Iniesta
Barca | Xavi
Barca | Iniesta
Barca | Puyol

所以我需要一个查询来检索每个团队中前两位常见的玩家。像这样的东西:

Team | Player
Barca | Messi
Barca | Iniesta
Chelsea | Lampard
Chelsea | Drogba

2 个答案:

答案 0 :(得分:4)

您可以使用子查询/ CTE计算每个玩家的计数和排名,方法是按照每个团队的计数降序对行进行编号。然后从每个团队中拉出前两名球员:

查询demo):

with ranks as (
  select
    team, player, count(*) as count,
    row_number() over (partition by team order by count(*) desc) as teamrank
  from players p
  group by team, player
)
select
  team, player
from
  ranks
where teamrank <= 2
order by team, teamrank

<强>结果:

|    TEAM |  PLAYER |
---------------------
|   Barca |   Messi |
|   Barca | Iniesta |
| Chelsea | Lampard |
| Chelsea |  Drogba |

答案 1 :(得分:3)

这是您想要窗口功能的地方:

select team, player
from (select team, player, count(*) as cnt,
             row_number() over (partition by team order by count(*) desc) as seqnum
      from team_player tp
      group by team, player
     ) tp
where seqnum in (1, 2)

请注意,这会在Windows函数中嵌套聚合函数count(*)