største-n-per-group spørgsmål løses normalt ved hjælp af vinduesfunktioner:
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;
Ovenstående er standard ANSI SQL, men i Postgres bruger den (proprietære) distinct on
er normalt meget hurtigere:
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