sql >> Base de Datos >  >> RDS >> PostgreSQL

SQL distintas columnas múltiples

las preguntas generalmente se resuelven usando funciones de ventana:

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 ANSI SQL estándar, pero en Postgres usando el (propietario) distinct on suele ser 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