将两列中的所有值相加并分组2分钟

时间:2019-05-24 16:57:43

标签: sql postgresql

我想对“值”列中的所有值求和,并以2分钟为间隔进行分组

我有这样的值:

value     TIME
0.3    2019-05-22 01:11:45---> first value 0,3
0.3    2019-05-22 01:12:16-----|
0.3    2019-05-22 01:13:26-----|second value 0,6
0.2    2019-05-22 01:13:56---|
0.4    2019-05-22 01:14:06---|
0.6    2019-05-22 01:15:43 --|third value 1,2

但是我真正想要的是这样的:

value     TIME
0.3    2019-05-22 01:11:45
0.6    2019-05-22 01:13:45
1.2    2019-05-22 01:15:45

我在Postgresql中的代码:

SELECT medi_sensor.value, time
FROM medi_sensor
    JOIN sensor ON medi_sensor.sensor_name = sensor.name
    JOIN mote ON num_mot=mot_id 
    JOIN room ON room_id=id_div
WHERE medi_sensor.sensor_name LIKE 'current%' AND room.name='DIV' AND time>'2019-05-22' AND time<'2019-05-24'
ORDER BY time ASC

问题是如何在我的时间列中按分钟分组

1 个答案:

答案 0 :(得分:1)

在Postgres中,您可以使用generate_series()来生成值:

select gs.t, sum(value)
from (select ms.value, time, min(time) over () as min_time, max(time) over () as max_time
      from medi_sensor ms join
            sensor s
            on ms.sensor_name = s.name join
            mote 
            on num_mot = mot_id join
            room r
            on room_id = id_div
      where ms.sensor_name LIKE 'current%' and
            r.name = 'DIV' and
            time > '2019-05-22' and
            time < '2019-05-24'
     ) x right join lateral
     generate_series(min_time, max_time, interval '2 minute') gs(t)
     on time >= gs.t and time < ts.t + interval '2 minute'
order by gs.t;

我建议您对查询中的所有列引用使用表别名。

编辑:

with x as (
      select ms.value, time
      from medi_sensor ms join
           sensor s
           on ms.sensor_name = s.name join
           mote 
           on num_mot = mot_id join
           room r
           on room_id = id_div
      where ms.sensor_name LIKE 'current%' and
            r.name = 'DIV' and
            time > '2019-05-22' and
            time < '2019-05-24'
     ) x 
select gs.ts, sum(x.value)
from (select generate_series(min_time, max_time, interval '2 minute') as ts
      from (select min(time) as min_time, max(time) as max_time
            from x
           )
      ) gs left join
      x
      on x.time >= gs.t and x.time < ts.t + interval '2 minute'
group by gs.ts
order by gs.ts;