【问题标题】:Reshape Postgres table, long to wide重塑 Postgres 表,从长到宽
【发布时间】:2019-03-19 17:02:52
【问题描述】:

考虑到 Postgres 9.5.1 中的以下时间序列数据,我正在尝试重塑为 array(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 来实现这个结果。非常感谢任何帮助。

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    您希望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
    

    【讨论】:

    • 而 lanl_train.time_to_failure = lanl_train.time_to_failure,如果有大约 150k 个不同的 time_to_failure(s)?
    • 我猜,更重要的是,acoustic_data的顺序是否保持?
    • 但 lanl_train.time_to_failure = lanl_train.time_to_failure 适用于 SELECT 15041
    • @Chris 对不起,我昨晚很忙,没有看到你的 cmets。我不确定你的第一个或第三个是什么意思,但 array_agg 确实保留了元组顺序,除非在 array_agg(table.column order by table.other_column asc) 这样的聚合函数中被覆盖
    • 效果很好,SELECT 15041 案例上保留了数组顺序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 2021-06-21
    • 1970-01-01
    • 2015-10-25
    • 2014-06-29
    • 2019-11-22
    相关资源
    最近更新 更多