I have following table with id(intger), project (varchar), month (varchar), hours (integer)
CREATE TABLE foo (id,project,month,hours)
AS VALUES
( 1 , 'A', 'aug', 1 ),
( 1 , 'A', 'sep', 3 ),
( 1 , 'B', 'aug', 2 ),
( 1 , 'B', 'sep', 5 ),
( 2 , 'A', 'aug', 2 ),
( 2 , 'A', 'sep', 4 );
I wanted below table
|id | project | aug | sep |
|1 | A | 1 | 3 |
|1 | B | 2 | 5 |
|2 | A | 2 | 4 |
I read this can be possible with an array but it seems like documentation is confusing. Can someone shed some light on this?
Best Answer
crosstab
doesn't permit composite keys. it requires rows provide a unique identifier for which to pivot them on. This means in your case(id,project)
has to be serialized. You can do this withjsonb
, or array or the like. Here I'm just using atext[]
.A couple of notes,
month
as adate.
There are lots of other ways you can solve this problem too without using crosstab,