sql - 对列中的所有值求和并按 2 分钟分组
问题描述
我想对列“值”中的所有值求和,并按 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
问题是如何在我的时间列中按分钟分组
解决方案
在 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;
推荐阅读
- python - 应该将哪些 URL 列入白名单以使用 conda 和 pip?
- sql - 在 sql 中存储项目分布
- reactjs - 如何使用 useRef() 进行验证
- python - 在 django 中编辑和更新用户模型
- java - JComboBox 错误阻止另一个字段显示
- postgresql - 带有子查询的 postgres case 语句
- ruby-on-rails - 如何修复 Rails 生产服务器中的 504 nginx 网关超时?
- rust - 克隆请求响应
- django - 通过侧边栏菜单项调用此表单时,从数据库模型填充 Django 表单字段标签
- angular - 在angular/typescript中根据id新建数组