I’ve got this table in Postgres:
create table test("Product id", "Product Name", "Category", "Operator", piece)
as values
(10, 'Carbonara', 'C1', 'User1', 1)
,(11, 'Spaghetti', 'C1', 'User2', 1)
,(12, 'Coke', 'C2', 'User1', 1)
,(10, 'Carbonara', 'C1', 'User2', 2)
,(11, 'Spaghetti', 'C1', 'User1', 1)
,(11, 'Spaghetti', 'C1', 'User3', 5)
,(12, 'Coke', 'C2', 'User3', 1)
;
I would like to have this result:
Category | User1 | User 2 | user 3 |
---|---|---|---|
C1 | 2 | 3 | 5 |
C2 | 1 | 0 | 1 |
I made some test with crosstab()
function, but didn’t get any result.
I’ve tried crosstab()
following some tutorial and answer here on SO, but I didn’t understand very well how to create this query.
2
Answers
You can pivot tables using an aggregate
filter
clause. Add acoalesce()
if you prefer to get a0
when a givenOperator
has no rows in a givenCategory
(all their rows would get filtered out beforesum()
):demo at db<>fiddle
Using
crosstab()
:Alternatively you can pivot into a single JSON object instead of several (number may vary) columns.
DB Fiddle demo