计算两个日期之间每小时每小时发生的次数

时间:2018-09-07 21:34:24

标签: sql-server tsql

我创建了一个临时表#MB,该表具有记录ID(119行),开始和结束日期(列表的部分屏幕截图如下):

enter image description here

我试图获取在开始和结束日期期间每个记录ID每小时发生的次数(或ID在两个日期之间处于活动状态时每小时发生的次数)。

我使用了以下代码:

SELECT *  
FROM  
    (SELECT  
         ISNULL(CAST(part AS VARCHAR(5)), 'Total') AS part,
         COUNT(*) AS part_count
     FROM    
         (SELECT DATEPART([HOUR], [Start]) AS part
          FROM #MB) grp
     GROUP BY
         GROUPING SETS((part),())
    ) pre
PIVOT   
    (MAX(part_count) 
         FOR part IN ([0], [1], [2], [3], [4], [5], [6], [7], [8],
                      [9], [10], [11], [12], [13], [14], [15], [16],
                      [17], [18], [19], [20], [21], [22], [23], Total)
    ) pvt;

,但是它仅基于开始日期计算记录(不计算两个日期之间的每个小时),并且我坚持如何为两个日期之间的每个ID每小时生成事件,我以后可以使用这些数据进行预汇总和枢。

enter image description here

1 个答案:

答案 0 :(得分:1)

首先,您需要生成每小时的行列表

在这里,我正在使用递归cte查询

; with MB as
(
    select  ID, [Start], [End], [Date] = [Start]
    from    #MB

    union all

    select  ID, [Start], [End], [Date] = dateadd(hour, 1, convert(date, c.[Date]))
    from    MB c
    where   dateadd(hour, 1, c.[Date])  < [End]
)
select  *
from    MB

因此,在您的数据透视查询中,只需更改为此

; with MB as
(
    select  ID, [Start], [End], [Date] = [Start]
    from    #MB

    union all

    select  ID, [Start], [End], [Date] = DATEADD(HH,DATEPART(HH,[Start]),CAST(CAST([Start] AS DATE) AS DATETIME))
    from    MB c
    where   dateadd(hour, 1, c.[Date])  < [End]
)
SELECT  *  
FROM    (
            SELECT  ISNULL(CAST(part AS VARCHAR(5)), 'Total')   AS part,
                    COUNT(*)            AS part_count
            FROM    (
                        SELECT  DATEPART([HOUR], [Date]) AS part
                        FROM    MB   -- changed to the cte
                    ) grp
            GROUP BY
                    GROUPING SETS((part),())
        ) pre
PIVOT   (MAX(part_count) FOR part IN (
            [0],[1],[2],[3],[4],[5],[6],[7],[8],
            [9],[10],[11],[12],[13],[14],[15],[16],
            [17],[18],[19],[20],[21],[22],[23], Total)) pvt;