遍历Postgres中的列

时间:2018-07-10 18:55:39

标签: 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

我的输出看起来应该像这样:

Stages               2015  2016
Under Construction    40    50
Completed              0    60 

我尝试了以下查询:

select sum(units) from table_1 where
stages = 'Under Construction' and year = 2016 ;

1 个答案:

答案 0 :(得分:1)

只需使用条件聚合:

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;