首页 > 解决方案 > 重塑 Postgres 表,从长到宽

问题描述

考虑到 Postgres 9.5.1 中的以下时间序列数据,我正在尝试将数组 (int) |time_to_failure(double) 重塑为新表

# SELECT acoustic_data, time_to_failure FROM lanl_train WHERE 
time_to_failure = '0.000795';
 acoustic_data | time_to_failure 
---------------+-----------------
             2 |        0.000795
             5 |        0.000795
             6 |        0.000795
             1 |        0.000795
             2 |        0.000795
             5 |        0.000795
             8 |        0.000795
             5 |        0.000795
             4 |        0.000795
             4 |        0.000795
             7 |        0.000795
             2 |        0.000795
             2 |        0.000795
             0 |        0.000795
             0 |        0.000795
             2 |        0.000795
             4 |        0.000795
             5 |        0.000795
             4 |        0.000795
(19 rows)

# SELECT ARRAY(SELECT acoustic_data FROM lanl_train WHERE 
time_to_failure = '0.000795');
                  array                  
-----------------------------------------
 {2,5,6,1,2,5,8,5,4,4,7,2,2,0,0,2,4,5,4}
(1 row)

这样新表中的一行将是

acoustic_data(array) | time_to_failure(double)
----------------------------------------------
{2,5,6,1,2,5,8,5,4,4,7,2,2,0,0,2,4,5,4} | 0.000795

我有一些零件,但被困在 SELECT 上以实现此结果。非常感谢任何帮助。

标签: sqlpostgresql

解决方案


您希望array_agg( docs ) 与一个分组:

select
    array_agg(lanl_train.acoustic_data) as acoustic_data,
    lanl_train.time_to_failure
from
    lanl_train
where
    lanl_train.time_to_failure = '0.000795'
group by
    lanl_train.time_to_failure

推荐阅读