I am looking to essentially create a pivot view using PostgreSQL, such that the table below:
Column A | Column B |
---|---|
Happy | Sad |
Sad | Happy |
Happy | Sad |
becomes
Count | Column A | Column B |
---|---|---|
Happy | 2 | 1 |
Sad | 1 | 2 |
I’ve been able to use case/when operators far enough such that I can see the counts under independent columns,
SELECT
COUNT(CASE WHEN column1 = 'Happy' THEN 1 END) AS column1_Happy_count,
COUNT(CASE WHEN column1 = 'Sad' THEN 1 END) AS column1_Sad_count,
COUNT(CASE WHEN column2 = 'Happy' THEN 1 END) AS column2_Happy_count,
COUNT(CASE WHEN column2 = 'Sad' THEN 1 END) AS column2_Sad_count,
COUNT(CASE WHEN column3 = 'Happy' THEN 1 END) AS column3_Happy_count,
COUNT(CASE WHEN column3 = 'Sad' THEN 1 END) AS column3_Sad_count
FROM your_table;
but am missing the step to essentially each the pair of columns vertically.
I’m unable to use extensions such as tablefunc and crosstab.
2
Answers
Try this:
will give you this:
You may aggregate for ColumnA, aggregate for ColumnB then do a full join as the following:
If the distinct values in ColumnA are the same as the distinct values of ColumnB then you can use join instead of the full join.
See demo.