terbesar-n-per-grup pertanyaan biasanya diselesaikan menggunakan fungsi jendela:
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;
Di atas adalah standar ANSI SQL, tetapi di Postgres menggunakan (bersifat eksklusif) distinct on
biasanya jauh lebih cepat:
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