Tengo una table como la siguiente:
book_id author_id mark year 1 1 BAD 2014 1 1 MEDIUM 2014 1 1 GREAT 2015
Me gustaría ejecutar una consulta que me proporcione el mejor libro para cada autor. Algo como esto:
book_id author_id mark year 1 1 GREAT 2015
Traté de usar la palabra key distinct en múltiples campos, pero cuando hago esto:
select distinct book_id, author_id from Books
Solo obtengo el book_id y el author_id (como se esperaba), pero también necesito la marca y el año, pero no puedo agregarlo a la frase distinta.
Actualmente estoy usando Postgres 9.4 pero necesito una solución ANSI-SQL.
¿Hay alguna manera de que pueda hacer eso?
las preguntas de mayor n-por-grupo generalmente se resuelven usando las funciones de window:
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;
Lo anterior es estándar ANSI SQL, pero en Postgres el uso del distinct on
(patentado) generalmente es mucho más rápido:
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