mysql 日期交集,SQL中的日期范围交集

I have a table where each row has a start and stop date-time. These can be arbitrarily short or long spans.

I want to query the sum duration of the intersection of all rows with two start and stop date-times.

How can you do this in MySQL?

Or do you have to select the rows that intersect the query start and stop times, then calculate the actual overlap of each row and sum it client-side?

To give an example, using milliseconds to make it clearer:

Some rows:

ROW START STOP

1 1010 1240

2 950 1040

3 1120 1121

And we want to know the sum time that these rows were between 1030 and 1100.

Lets compute the overlap of each row:

ROW INTERSECTION

1 70

2 10

3 0

So the sum in this example is 80.

解决方案

If your example should have said 70 in the first row then

assuming @range_start and @range_end as your condition paramters:

SELECT SUM( LEAST(@range_end, stop) - GREATEST(@range_start, start) )

FROM Table

WHERE @range_start < stop AND @range_end > start

using the greatest/least and date functions you should be able to get what you need directly operating on the date type.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值