计算相邻记录的间隔

该博客介绍了如何使用SQL查询从包含开始和结束状态的时间序列数据中计算时间差,特别是如何确保只选取每一对最先出现的开始和结束状态,而不将多个事件合并成一个时间段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【问题】
I have a table structured like this

index   date time status
1 2015-01-01 13:00:00 start
2 2015-01-01 13:10:00 continue
3 2015-01-01 13:20:00 continue
4 2015-01-01 13:30:00 end
5 2015-01-01 13:30:00 ready
6 2015-01-01 13:40:00 start
7 2015-01-01 13:50:00 continue
8 2015-01-01 15:00:00 end`

and what I would like to do is count the time between start and end (ie. index 1-4 is 30min, 6-8 is 20min), but taking into account only the first start and first end, so that the query doesn’t choose the time difference of index 1-8. Which query is used to calculate time difference between two statues (start-end) and show the result for multiple instances of start-end without them getting batched into one event?

正确答案:

SELECT x.*
 , TIMEDIFF(MIN(y.dt),x.dt)diff
 FROM my_table x
 JOIN my_table y
 ON y.dt >= x.dt
WHERE x.status = 'start'
 AND y.status = 'end'
GROUP
 BY x.id;

【回答】

SQL 做这种有序的运算很麻烦,所以可以选用集算器来实现,代码简单易懂:

A
1$select * from tb1
2=A1.group((#-1)\2)
3=A2.new(~(1).time:start,~(2).time:end,interval@s(start,end)/60:diff)

A3:计算时间差,生成新序表

集算器提供 JDBC 接口,可以像数据库一样嵌入到应用程序中,用起来很简单,可参考Java 如何调用 SPL 脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值