Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 在Postgres中的列上循环_Sql_Postgresql_Pivot_Crosstab - Fatal编程技术网

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;

如果我想计算每一阶段的全年总收入呢??