如何在postgres中使用Pivot

时间:2016-03-04 13:41:33

标签: sql postgresql pivot crosstab

我需要在postgres中使用pivot,下面是基表

enter image description here

以下是所需的输出

enter image description here

请帮我查询。

2 个答案:

答案 0 :(得分:1)

这实际上是一个非枢轴,而非枢轴

select year, week, 'loading' as area, loading as value
from the_table
union all
select year, week, 'picking', picking
from the_table
union all
select year, week, 'painting', painting
from the_table

答案 1 :(得分:0)

如果您只需要转动3列,请使用union

select year,week,'loading' as aread,loading as val from tbl
union all
select year,week,'painting' as area,painting as val from tbl
union all
select year,week,'picking' as area,picking as val from tbl

如果列数是动态的,那么我建议您使用动态数据透视表。

Dynamic pivot query using PostgreSQL 9.3

http://www.cureffi.org/2013/03/19/automatically-creating-pivot-table-column-names-in-postgresql/