greatest-n-per-group vragen worden meestal opgelost met behulp van vensterfuncties:
select *
from (
select book_id, author_id, mark, year,
row_number() over (partition by author_id order by case mark when 'GREAT' then 1 when 'MEDIUM' then 2 else 3 end) as rn
from books
) t
where rn = 1;
Het bovenstaande is standaard ANSI SQL, maar in Postgres met de (eigen) distinct on
is meestal veel sneller:
select distinct on (author_id) book_id, author_id, mark, year,
from books
order by author_id,
case mark when 'GREAT' then 1 when 'MEDIUM' then 2 else 3 end