【问题标题】:Calculation of total duration of events for a day计算一天事件的总持续时间
【发布时间】:2011-10-25 20:20:12
【问题描述】:

我们有一个名为 Events 的表,其中包含 Id(int)、EventDate(DateTime)、EventStart(datetime) 和 EventEnd(datetime) 列。

所有事件都在一天开始和结束(即没有事件在第二天结束),但是给定日期的事件可能会在它们之间重叠(包括其中一个可以完全覆盖另一个)。

在给定日期可能发生任意数量的事件。

我想计算一天中至少一个事件在 T-SQL 中运行的总持续时间。我可以选择给定日期的事件,甚至编写了一个函数,如果两个事件重叠则返回 true,否则返回 false。

然而,我被困在如何将记录成对并通过我的函数运行,适当地添加持续时间,直到我用完事件。

你能帮忙吗?

克里斯

【问题讨论】:

  • 你能给出一些示例数据和一些预期的输出吗?我不确定我是否按照您的要求进行操作。

标签: tsql


【解决方案1】:

试试这个:

--test table
declare @t table(fromt datetime, tot datetime)
--test data
insert @t values('2011-01-01 10:00', '2011-01-01 11:00')
insert @t values('2011-01-01 10:00', '2011-01-01 10:05')
insert @t values('2011-01-01 10:30', '2011-01-01 11:30')
insert @t values('2011-01-01 12:00', '2011-01-01 12:30')
insert @t values('2011-01-02 12:00', '2011-01-02 12:30')

--query
;with f as
(
    select distinct fromt from @t t 
    where not exists(select 1 from @t where t.fromt > fromt and t.fromt < tot)
), t as
(
    select distinct tot from @t t 
    where not exists(select 1 from @t where t.tot >= fromt and t.tot < tot)
), s as
(
    select datediff(day, 0, fromt) d, datediff(second, fromt, (select min(tot) 
      from t where f.fromt < tot and datediff(day, f.fromt, tot) = 0)) sec 
    from f
)
select dateadd(day, 0, d) day, sum(sec)/60 [minutes]
from s
group by d
order by d

结果:

day                     minutes
----------------------- -------
2011-01-01 00:00:00.000 120
2011-01-02 00:00:00.000 30

【讨论】:

  • 优秀的答案。第一次像魅力一样工作!谢谢。
猜你喜欢
  • 2021-10-14
  • 1970-01-01
  • 2019-07-21
  • 1970-01-01
  • 2018-03-04
  • 1970-01-01
  • 1970-01-01
  • 2014-01-14
  • 1970-01-01
相关资源
最近更新 更多