I have following table:
|Type | Year | amount |
_______________________
|t1 | 2001 | 40 |
|t1 | 2000 | 50 |
|t2 | 2003 | 30 |
|t2 | 2003 | 20 |
|t3 | 2004 | 10 |
and I would like to show it as:
| type |2001 |2000 |2003 |2004|
|______________________________
| t1 |40 |50 |0 |0 |
| t2 | 0 |0 | 50 |0 |
| t3 |0 |0 | 0 |10 |
I don't want to hard code the years and I need to do that in POstgresql 8.4, which doesn't support:
CREATE EXTENSION
IF NOT EXISTS tablefunc;
I have pivoted table before, using following code: more explanation for the following code is here
sum(CASE
WHEN year = 2000 THEN
total
ELSE 0
END)
In which the total =sum (amount)
in each year and I had calculated it in another CTE. But at that time the years were already known but for the above table I need to loop through the years and read each and then calculate the sum(amount)
and the years may change in the main table.