PostgreSQL
 sql >> Base de Dados >  >> RDS >> PostgreSQL

Como juntar apenas uma linha na tabela unida com postgres?

select distinct on (author.id)
    book.id, author.id, author.name, book.title as last_book
from
    author
    inner join
    book on book.author_id = author.id
order by author.id, book.id desc

Verifique distinct on

Com distinct ativado é necessário incluir as colunas "distintas" na order by . Se esse não for o pedido que você deseja, você precisa agrupar a consulta e reordenar
select 
    *
from (
    select distinct on (author.id)
        book.id, author.id, author.name, book.title as last_book
    from
        author
        inner join
        book on book.author_id = author.id
    order by author.id, book.id desc
) authors_with_first_book
order by authors_with_first_book.name

Outra solução é usar uma função de janela como na resposta de Lennart. E outra muito genérica é essa
select 
    book.id, author.id, author.name, book.title as last_book
from
    book
    inner join
    (
        select author.id as author_id, max(book.id) as book_id
        from
            author
            inner join
            book on author.id = book.author_id
        group by author.id
    ) s
    on s.book_id = book.id
    inner join
    author on book.author_id = author.id