mssql 30 minute time intervals beteen 2 datetime

前端 未结 5 1464
余生分开走
余生分开走 2021-01-25 03:10

I have below query and i want to get datetime in 30 min intervals between 2 datetime. Basicly I got it, but is limitited and wouln\'t return al results if the timediff is over 2

5条回答
  •  被撕碎了的回忆
    2021-01-25 03:26

    A tally table is a great way to deal with this type of thing. I keep one in a view to avoid using spt_values.

    create View [dbo].[cteTally] as
    
    WITH
        E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
        E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
        E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
        cteTally(N) AS 
        (
            SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
        )
    select N from cteTally
    

    Then your code becomes really simple too. A small amount of datemath and voila.

    declare @DateTime1 datetime = '2016/11/24 18:00:00'
        , @DateTime2 datetime = '2016/11/25 06:00:00'
    
    select FORMAT(DATEADD(minute, (t.N - 1) * 30, @DateTime1), 'dd-HH:mm')
    from cteTally t
    where t.N <= (DATEDIFF(hour, @DateTime1, @DateTime2) * 2) + 1
    

提交回复
热议问题