0

I have a table in PostgreSQL called flights:

id  city
101 Cairo
101 Paris
102 Madrid
102 Helsinki
103 Sydney
103 Kuala Lumpur
104 Cape Town
104 Beijing

I need to be able to group by 'id' and add every city as a separate column, like this:

id  city1       city2
101 Cairo       Paris
102 Madrid      Helsinki
103 Sydney      Kuala Lumpur
104 Cape Town   Beijing

Inspired by this answer I have tried the following:

SELECT * FROM crosstab(
   $$SELECT id, city, rn
     FROM  (
        SELECT u.id, u.city,

              row_number() OVER (
                        PARTITION BY u.id
                        ORDER BY e.id
                        DESC NULLS LAST
                        ) AS rn

        FROM flights u
        
        LEFT JOIN flights e USING (id)
        
        ) sub
     WHERE  rn < 4
     ORDER  BY id
   $$
  , 'VALUES (1),(2)'
   ) AS t (id int, city1 text, city2 text);

But my resultant city1 and city2 fields are empty - pls help!

wimbo
  • 1
  • 1

0 Answers0