gpt4 book ai didi

sql - 计算重叠时间范围内的分钟数总和

转载 作者:行者123 更新时间:2023-12-04 22:28:54 24 4
gpt4 key购买 nike

我需要计算术语的分钟总和。重叠的术语不应多次计算。

Declare @Terms table (Start DATETIME, Finish DATETIME)
INSERT INTO @Terms values
('2016-8-3 08:00','2016-8-3 09:00'),
('2016-8-3 09:00','2016-8-3 10:00'),
('2016-8-3 08:00','2016-8-3 09:30'), -- overlapping term
('2016-8-3 11:00','2016-8-3 12:00')

以上数据的结果应该是 180 分钟(3 小时)。最简单和最快的方法是什么?

最佳答案

在交叉申请的帮助下。

Declare @Terms table (Start DATETIME, Finish DATETIME)
INSERT INTO @Terms values
('2016-8-3 08:00','2016-8-3 09:00'),
('2016-8-3 09:00','2016-8-3 10:00'),
('2016-8-3 08:00','2016-8-3 09:30'), -- overlapping term
('2016-8-3 11:00','2016-8-3 12:00')

Select Minutes = sum(Minutes)
From (
Select Distinct
B.DateR1
,B.DateR2
,Minutes = DateDiff(Minute,B.DateR1,B.DateR2)
From @Terms A
Cross Apply (
Select DateR1=Min(Start)
,DateR2=max(Finish)
From @Terms
Where Start <= A.Finish and Finish >= A.Start
) B
) A

退货
Minutes
180

子查询返回
DateR1                     DateR2                   Minutes
2016-08-03 08:00:00.000 2016-08-03 10:00:00.000 120
2016-08-03 11:00:00.000 2016-08-03 12:00:00.000 60

关于sql - 计算重叠时间范围内的分钟数总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38748332/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com