PostgreSQL
 sql >> Datenbank >  >> RDS >> PostgreSQL

Gruppieren nach und Spalten hinzufügen

Ich neige dazu, diese Art von Abfrage mit bedingter Aggregation anzugehen:

select ward,
       max(case when seqnum = 1 then councillor end) as councillor1,
       max(case when seqnum = 2 then councillor end) as councillor2,
       max(case when seqnum = 3 then councillor end) as councillor3
from (select wc.*,
             row_number() over (partition by ward order by councillor) as seqnum
      from ward_councillors wc
     ) wc
group by ward;