我有几张桌子
表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语句?
最佳答案
可以使用条件聚合:
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;
关于sql - Postgres生成一系列列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58719653/