gpt4 book ai didi

postgresql - 让这个 group by 和 max 查询工作

转载 作者:行者123 更新时间:2023-11-29 12:20:19 26 4
gpt4 key购买 nike

我有下表 players :

ID;color;race;score
1;"red";"elf";400
2;"blue";"elf";500
3;"green";"elf";300
4;"blue";"elf";200
5;"red";"elf";700
6;"red";"troll";100
7;"blue";"troll";400
8;"green";"troll";500
9;"red";"troll";400
10;"yellow";"troll";1000
11;"red";"nord";900
12;"green";"nord";100
13;"yellow";"nord";500
14;"blue";"nord";7000

我想要每场比赛的最高得分以及该球员的颜色和 ID。像这样

elf 700 red 5
nord 7000 blue 14
troll 1000 yellow 10

我可以获得的前两列:

select category,max(score)
from players
group by category;

但我无法添加该播放器的颜色和 ID。我该怎么做?

最佳答案

你可以使用RANK函数:

WITH cte AS
(
SELECT *, RANK() OVER(PARTITION BY race ORDER BY score DESC) AS r
FROM players
)
SELECT race, score, color, id
FROM cte
WHERE r = 1;

LiveDemo

输出:

╔═══════╦═══════╦════════╦════╗
║ race ║ score ║ color ║ id ║
╠═══════╬═══════╬════════╬════╣
║ elf ║ 700 ║ red ║ 5 ║
║ nord ║ 7000 ║ blue ║ 14 ║
║ troll ║ 1000 ║ yellow ║ 10 ║
╚═══════╩═══════╩════════╩════╝

关于postgresql - 让这个 group by 和 max 查询工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29498647/

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