Postgres生成一系列列

时间:2019-11-05 21:21:42

标签: sql postgresql pivot

我有几张桌子

表1:

meter_id  |    date 
    1       2019-01-01

表2:

meter_id  |  read_date   |  period   |  read   
   1         2019-01-01       1          5
   1         2019-01-01       2          6
   1         2019-01-01       5          2
   1         2019-01-01       6          1
   1         2019-01-01       7          2
   2         2019-01-01       1          3
   2         2019-01-01       2          10
   1         2019-01-02       6          7

是否可以生成一系列列,所以我最终得到这样的结果:

meter_id  |  read_date  |  p_1  |  p_2   |  p_3  |  p_4  |  p_5  |  p_6   ...
   1         2019-01-01     5       6                        2       1
   2         2019-01-01     3       10     
   1         2019-01-02                                              7     

每天(每半小时)读取48次

无需执行多个select语句?

1 个答案:

答案 0 :(得分:2)

您可以使用条件聚合:

select t1.meter_id, t1.date,
       max(t2.read) filter (where period = 1) as p_1,
       max(t2.read) filter (where period = 2) as p_2,
       max(t2.read) filter (where period = 3) as p_3,
       . . .
from table1 t1 join
     table2 t2
     on t1.meter_id = t2.meter_id and t1.date = t2.read_date
group by t1.meter_id, t1.date;