I am new to SQL and trying to do a crosstab in Postgres. I would do it in Excel, but I have a database of about 3.5 million rows, 20,000 different values for the code, 7 categories in cat and variable values from 1 to 100. The code can only have a few of 7 categories.
Excel cannot handle the number of rows, so SQL is.
My details are in the form
code | cat | value |
--------------------------------
abc123 | 1 | 4 |
abc234 | 2 | 6 |
abc345 | 1 | 1 |
abc123 | 3 | 2 |
abc123 | 6 | 12 |
with code and cat as text, the value as an integer stored in a Postgres table.
I would like to do a crosstab for code and cat with the sum of the value. I would like it to display null instead of "null" in the return, but if "null" would be a simpler query, then that would be fine.
So I would like to get
code | 'cat=0' | 'cat=1' | 'cat=2' | 'cat=3' | 'cat=4' | 'cat=5' | 'cat=6'|
abc123 | 25 | 0 | 3 | 500 | 250 | 42 | 0 |
abc234 | 0 | 100 | 0 | 10 | 5 | 0 | 25 |
abc345 | 1000 | 0 | 0 | 0 | 0 | 0 | 0 |
Postgres ; SO PostgreSQL Crosstab Query, , .
.