How do you group by any time based interval?

后端 未结 1 2068
不知归路
不知归路 2020-12-11 14:20

In SQL SERVER How do you group by any time based interval?

To save someone time I have come up with this solution, For me it works very well. You can generate any ti

相关标签:
1条回答
  • 2020-12-11 14:43

    I think you are over complicating thins.
    You can use GROUP BY (DATEDIFF(MINUTE, '2017-01-01', TheDateTime) / 30 for grouping by every 30 minutes. Of course, the date I've chosen is a just a random date. You can choose, if you want, the first (or last) date in your sample data.
    And you can also use this technique to get every interval of any time part - just change the keyword MINUTE to any date part you want to use, and the intreval 30 to any interval you want.

    Consider the following sample data:

    ;WITH CTE AS 
    (
        SELECT CAST('2017-01-01T00:00:00' as datetime) As TheDateTime, 0 as rn
        UNION ALL
        SELECT DATEADD(MINUTE, 1, TheDateTime), rn + 1
        FROM CTE
        WHERE rn < 60
    )
    
    SELECT TheDateTime, rn INTO #T
    FROM CTE
    OPTION(MAXRECURSION 0)
    

    #T now contains the following data:

    TheDateTime                 rn
    2017-01-01 00:00:00.000     0
    2017-01-01 00:01:00.000     1
    2017-01-01 00:02:00.000     2
    2017-01-01 00:03:00.000     3
    ...
    2017-01-01 00:59:00.000     59
    2017-01-01 01:00:00.000     60
    

    To get the maximum rn grouped by 30 minutes you just need this:

    SELECT DATEDIFF(MINUTE, '2017-01-01', TheDateTime) / 30, MAX(rn)
    FROM #T
    GROUP BY DATEDIFF(MINUTE, '2017-01-01', TheDateTime) / 30
    

    Results:

    interval    max_rn
    0           29
    1           59
    2           60
    
    0 讨论(0)
提交回复
热议问题