如何将行组转换为单独的列?

时间:2014-06-25 13:29:35

标签: postgresql postgresql-9.3

我有一个postgresql表,如下所示:

a|b|c|result
0|3|6|50
0|3|7|51
0|4|6|52
0|4|7|53
1|3|6|54
1|3|7|55
1|4|6|56
1|4|7|57

有一种简单的方法可以选择以下内容:

a|result for b=3|result for b=4
0|sum(50,51)    |sum(52,53)
1|sum(54,55)    |sum(56,57)

换句话说,如何将b的值组转换为聚合函数的列,如sum(),avg()或其他?

感谢您的评论。

1 个答案:

答案 0 :(得分:2)

我不确定我是否完全理解您的问题,但我认为您正在寻找case

-- drop table if exists sample;

create table sample
  (a int,
   b int,
   c int,
   result int);

insert into sample values
(0,3,6,50),
(0,3,7,51),
(0,4,6,52),
(0,4,7,53),
(1,3,6,54),
(1,3,7,55),
(1,4,6,56),
(1,4,7,57)
;

select
  a,
  sum(case when b = 3 then result end) as result_for_b3,
  sum(case when b = 4 then result end) as result_for_b4
from
  sample
group by
  a

结果:

a;result_for_b3;result_for_b4
1;109;113
0;101;105

如果你(但我希望你没有)需要完全按照你的问题输出,那么你需要使用string_agg函数:

select
  a,
  'aggreg(' || string_agg(case when b = 3 then result end::varchar, ',') || ')' as result_for_b3,
  'aggreg(' || string_agg(case when b = 4 then result end::varchar, ',') || ')' as result_for_b4
from
  sample
group by
  a

结果:

a;result_for_b3;result_for_b4
0;aggreg(50,51);aggreg(52,53)
1;aggreg(54,55);aggreg(56,57)