greatest-n-per-group 質問は通常、ウィンドウ関数を使用して解決されます:
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;
上記は標準のANSISQLですが、Postgresでは(独自の)distinct on
を使用しています 通常ははるかに高速です:
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