Search code examples
sqlpostgresqlgreatest-n-per-group

SQL: Efficient way to get group by results including all table columns


Let's consider a simple table below.

id code marks grade
1 X 100 A
2 Y 120 B
3 Z 130 A
4 X 120 C
5 Y 100 A
6 Z 110 B
7 X 150 A
8 X 140 C

Goal: Get maximum marks for each grade, return all the columns.

id code marks grade
7 X 150 A
2 Y 120 B
8 X 140 C

This is very simple if I don't want id and code column

select grade, max(marks)
from table
group by grade;

What could be the most efficient query to get id and code column in the above query?

I tried something like this which didn't work

select * from table t
inner join
(select grade, max(marks)
from table
group by grade) a
on a.grade=t.grade;

Solution

  • In Postgres the most efficient way for this kind of query is to use (the proprietary) distinct on ()

    select distinct on (grade) *
    from the_table t
    order by grade, marks desc;