Sql 带开始时间和结束时间的时间桶
我有这样的数据Sql 带开始时间和结束时间的时间桶,sql,postgresql,datetime,count,timescaledb,Sql,Postgresql,Datetime,Count,Timescaledb,我有这样的数据 machine,start,end A, 00:00, 00:01 B, 00:01, 00:02 C, 00:00, 00:03 我想为绘制图表进行汇总 start, end, value 00:00, 00:01, 2 00:01, 00:02, 2 00:02, 00:03, 1 该值是开始-结束持续时间内机器工作的数量。我试着利用时间、水桶和缺口 但是这个函数只使用一列。我应该使用哪个函数来完成此操作 谢谢 -------更多示例 machine,start,end
machine,start,end
A, 00:00, 00:01
B, 00:01, 00:02
C, 00:00, 00:03
我想为绘制图表进行汇总
start, end, value
00:00, 00:01, 2
00:01, 00:02, 2
00:02, 00:03, 1
该值是开始-结束持续时间内机器工作的数量。我试着利用时间、水桶和缺口
但是这个函数只使用一列。我应该使用哪个函数来完成此操作
谢谢
-------更多示例
machine,start,end
A, 00:00:00, 00:01:00
F, 00:00:30, 00:01:30
B, 00:01:00, 00:02:00
C, 00:00:00, 00:03:00
结果应该是
start, end, value
00:00, 00:01, 3
00:01, 00:02, 3
00:02, 00:03, 1
在Postgres中,可以通过取消激发行,然后计算:
select
x.tt as t_start,
lead(x.tt) over(order by x.tt) as t_end,
sum(sum(cnt)) over(order by x.tt) val
from mytable t
cross join lateral (values (t.t_start, 1), (t.t_end, -1)) x(tt, cnt)
group by x.tt
在Postgres中,可以通过取消激发行,然后计算:
select
x.tt as t_start,
lead(x.tt) over(order by x.tt) as t_end,
sum(sum(cnt)) over(order by x.tt) val
from mytable t
cross join lateral (values (t.t_start, 1), (t.t_end, -1)) x(tt, cnt)
group by x.tt
使用Generate_系列生成分钟间隔,然后左连接:
使用Generate_系列生成分钟间隔,然后左连接:
我增加了更多的例子,你能检查一下吗?谢谢alot@rura6502 . . . 将逻辑中的分钟替换为秒。我添加了更多示例,您能检查一下吗?谢谢alot@rura6502 . . . 只要在逻辑中将分钟替换为秒。我认为查询缺少group by-see我认为查询缺少group by-see
select m.second as start,
m.second + interval '1 second' as end,
count(t.machine)
from (select generate_series(min('00:' || start), max('00:' || end), interval '1 second') as second
from t
) m left join
t
on m.second < t.end and
m.second >= t.start
group by m.second
order by m.second;