TSQL:日期时间重叠和间隔值

时间:2010-02-02 18:54:53

标签: sql-server-2005 tsql

需要帮助来为此创建查询。

Start               | End
2009-01-01 06:00:00 | 2009-01-01 14:00:00
2009-01-01 06:00:00 | 2009-01-02 06:00:00
2009-01-02 07:00:00 | 2009-01-02 08:00:00
2009-01-03 06:00:00 | 2009-01-03 14:00:00
2009-01-03 09:00:00 | 2009-01-03 11:00:00
2009-01-04 22:00:00 | 2009-01-05 06:00:00
2009-01-05 01:00:00 | 2009-01-05 10:00:00

我希望间隔时间不重叠(2009-01-01 00:00:00 - 2009-01-31 00:00:00) 每天的总和是这样的:

Date       | Duration
2009-01-01 | 18
2009-01-02 | 7
2009-01-03 | 8
2009-01-04 | 2
2009-01-05 | 10

然后查找每个请求间隔的总和。

您是否能够帮助构建此查询?

2 个答案:

答案 0 :(得分:1)

试试这个:

WITH Times AS (
        SELECT DISTINCT(Start) AS Time FROM intervals
        UNION ALL
        SELECT DISTINCT([End]) AS Time FROM intervals),
     Days AS (SELECT DISTINCT DATEADD(dd, 0, DATEDIFF(dd, 0, Time)) AS Time FROM Times),
     Times2 AS (
        SELECT Time FROM times
        UNION ALL
        SELECT Time FROM days),
     Times3 AS (SELECT ROW_NUMBER() OVER (ORDER BY Time) AS rn, Time FROM Times2),
     Times4 AS (
        SELECT T1.Time AS Start, T2.Time AS [End]
        FROM Times3 T1
        JOIN Times3 T2
        ON T1.rn + 1 = T2.rn),
     IntervalParts AS (
         SELECT DISTINCT Times4.*
         FROM Times4
         JOIN intervals
         ON Times4.Start >= intervals.Start AND Times4.[End] <= intervals.[End]),
     IntervalsByDay AS (
         SELECT 
             DATEADD(dd, 0, DATEDIFF(dd, 0, Start)) AS Day,
             DATEDIFF(hh, Start, [End]) AS Duration 
         FROM IntervalParts)
SELECT Day, SUM(Duration) AS Duration
FROM IntervalsByDay
GROUP BY Day

结果:

Day                     Duration 
2009-01-01 00:00:00.000 18
2009-01-02 00:00:00.000 7
2009-01-03 00:00:00.000 8
2009-01-04 00:00:00.000 2
2009-01-05 00:00:00.000 10

要将其限制在特定范围内,只需添加适当的WHERE子句。

答案 1 :(得分:0)

在sqlserver中查看DATEDIFF。我不确定你正在使用什么数据库服务器,但我想其他RDBMS会有类似或足够的东西,你可以创建自己的函数来做到这一点。

SELECT start, DATEDIFF(hh, start, end) FROM ......

看起来我错过了这个的多日期部分。要把它拆分几天,我想你几乎必须分别处理每个记录并存储在临时表或其他东西中。也许你可以创建一个函数,为每个记录返回一个表,按日期分割持续时间,然后每个日期可以是SUMMED。?