Sql 在Postgres中的列上循环
我的桌子像:Sql 在Postgres中的列上循环,sql,postgresql,pivot,crosstab,Sql,Postgresql,Pivot,Crosstab,我的桌子像: Name Stages Year Units P1 Under Construction 2015 10 P2 Completed 2016 20 P3 Under Construction 2015 30 P4 Completed 2016 40 P5 Under Construction 2016 50 我的输出在某种程度上应该如下所示:
Name Stages Year Units
P1 Under Construction 2015 10
P2 Completed 2016 20
P3 Under Construction 2015 30
P4 Completed 2016 40
P5 Under Construction 2016 50
我的输出在某种程度上应该如下所示:
Stages 2015 2016
Under Construction 40 50
Completed 0 60
我尝试了如下查询:
select sum(units) from table_1 where
stages = 'Under Construction' and year = 2016 ;
只需使用条件聚合:
select stages,
sum(case when year = 2015 then units else 0 end) from units_2015,
sum(case when year = 2016 then units else 0 end) from units_2016
from t
group by stages;
如果我想计算每一阶段的全年总收入呢??