I am new to postgresql and even newer to crosstab but from what I have read, the below query should work:
select * from crosstab(
$$select distinct "AccountNumber" , "ProductCategory", sum("ProductQuantity") sm
from "MsfDataRecords" mdr
group by "ProductCategory", "AccountNumber", "ProductQuantity"$$
)as ct("AccountNumber" text , "ProductCategory" text , sm numeric)
But this errors with SQL Error [42601]: ERROR: return and sql tuple descriptions are incompatible
I have checked all the data types and they are correct. I'm not sure if it is to do with the sum function though.
Any help appreciated
The error is in the last line. The columns represented in the ct are selected in this line. Instead of
it should be
Your
GROUP BYclause also should only include the first and second column which are later on sorted.Here's a dbfiddle example for illustration. Or if you prefer code here's an example code.
Note that pivoting like this only works in PostgreSQL.