Skip to content Skip to sidebar Skip to footer

Postgres Simple 'pivot' Table

If I have a table of data as such name | type | count test | blue | 6 test2 | red | 3 test | red | 4 How can I query it such that I get a table: name

Solution 1:

You can use CASE in you select clause.

SELECT  name,
        SUM(CASE WHEN type = 'red' THEN "count" ELSE 0 END) numred,
        SUM(CASE WHEN type = 'blue' THEN "count" ELSE 0 END) numblue
FROM tableName
GROUP BY name

SQLFiddle Demo


Post a Comment for "Postgres Simple 'pivot' Table"