gpt4 book ai didi

sql - 基于其他列的最常见的 2 个值

转载 作者:行者123 更新时间:2023-12-02 07:38:11 24 4
gpt4 key购买 nike

我有这张表:

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

最佳答案

您可以使用子查询/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 |

关于sql - 基于其他列的最常见的 2 个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14047088/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com