Search code examples
sqlpostgresqlpivotcrosstabpostgresql-9.4

How to transform rows to columns using Postgres SQL?


I have the data in the following structure Question

Desired Output

https://imgur.com/a/855njBn][1]


Solution

  • Postgres (starting in 9.4) supports the filter syntax for conditional aggregation. So I would recommend:

    SELECT customer_id,
           MAX(value) FILTER (WHERE name = 'age') as age,
           MAX(value) FILTER (WHERE name = 'marketing_consent') as marketing_consent,
           MAX(value) FILTER (WHERE name = 'gender') as gender
    FROM t
    GROUP BY customer_id