2

I have the following table players with an:

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

I want per race, the maximum score and the color and ID of that player. Like this

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

The first two column I can get with:

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

But I'm unable to add the color and ID of that player. How do I do this?

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
Bosiwow
  • 2,025
  • 3
  • 28
  • 46
  • possible duplicate of [How to select id with max date group by category in PostgreSQL?](http://stackoverflow.com/questions/16914098/how-to-select-id-with-max-date-group-by-category-in-postgresql) – Jakub Kania Apr 07 '15 at 18:41
  • We don't know your column names but why wouldn't the following just work: `select category,max(score), max(id), max(color) from players group by category;` – Simo Kivistö Apr 07 '15 at 18:42

1 Answers1

1

You can use RANK function:

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

Output:

╔═══════╦═══════╦════════╦════╗
║ race  ║ score ║ color  ║ id ║
╠═══════╬═══════╬════════╬════╣
║ elf   ║   700 ║ red    ║  5 ║
║ nord  ║  7000 ║ blue   ║ 14 ║
║ troll ║  1000 ║ yellow ║ 10 ║
╚═══════╩═══════╩════════╩════╝
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275