2

我有这张桌子:

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
4

2 回答 2

4

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

查询演示):

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 |
于 2012-12-26T22:41:23.587 回答
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)

请注意,这将聚合函数嵌套count(*)在 windows 函数中。

于 2012-12-26T22:41:59.593 回答