我的下表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。我该怎么做?
答案 0 :(得分:1)
您可以使用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 ║
╚═══════╩═══════╩════════╩════╝