将列数据排列成postgres中的行

时间:2018-04-26 09:15:49

标签: sql postgresql pivot crosstab

我有一张下表数据表: -

t,me,ma,mi,sd,data_id
'2010-04-14 00:00:00','12.6941','12.6941','12.6941','12.6941',1
'2010-04-14 00:00:00','12.3851','12.3851','12.3851','12.3851',2
'2010-04-14 00:00:00','11.6145','11.6145','11.6145','11.6145',3
'2010-04-14 00:10:00','12.3890','12.3890','12.3890','12.3890',1
'2010-04-14 00:10:00','12.1836','12.1836','12.1836','12.1836',2
'2010-04-14 00:10:00','11.3887','11.3887','11.3887','11.3887',3

我希望数据排列如下: -

t,1_me,1_ma,1_mi,1_sd,2_me,2_ma,2_mi,2_sd,3_me,3_ma,3_mi,3_sd
'2010-04-14 00:00:00','12.6941','12.6941','12.6941','12.6941','12.3851','12.3851','12.3851','12.3851','11.6145','11.6145','11.6145','11.6145'
'2010-04-14 00:10:00','12.3890','12.3890','12.3890','12.3890','12.1836','12.1836','12.1836','12.1836','11.3887','11.3887','11.3887','11.3887'

有人可以帮我订购这些数据吗?

1 个答案:

答案 0 :(得分:0)

select t,listagg(me||','||ma||','||mi||','||sd,',') within group(order by t)  
from table_name 
group by t  
order by t;

我在Oracle中使用过这个,同样你可以在Postgres中使用等效的string_agg()函数。