How to get the records grouping dates for a span of 3 days in SQL?

后端 未结 2 419
抹茶落季
抹茶落季 2021-01-23 11:07

It\'s getting difficult to group and display records every 5 days.

Here is my data:

FLIGHT         


        
相关标签:
2条回答
  • 2021-01-23 11:21

    Here it is my proposed solution:

    DECLARE @MinDate AS DATETIME = (SELECT MIN(flight_date) FROM flights);
    
    WITH cte
    AS
    (
        SELECT
            flight_date, DATEDIFF(DAY, @MinDate, flight_date) AS NoDays,
            DATEDIFF(DAY, @MinDate, flight_date)/5 AS NoGroup,
            DPT
        FROM flights
    )
    SELECT  
        DATEADD(DAY, NoGroup*5, @MinDate) AS [Week Start],
        DATEADD(DAY, NoGroup*5+4, @MinDate) AS [Weed End],  
        SUM(DPT)
    FROM cte
    GROUP BY NoGroup;
    

    The idea is to form groups of 5 days, then associate a record to a specific group based on division with 5. NoDays represents the days spent from MinDate to Flight_Date.

    0 讨论(0)
  • 2021-01-23 11:33

    You can use this query. You need to specify the start date from which you want to count and the number of days in each period (which seems to be 5 in your case) but please adjust those numbers as needed.

    declare @startdate date = '20131117'
    declare @interval int = 5
    
    select dateadd(dd, @interval * (o.number - 1), @startdate) WeekStart, 
        dateadd(dd, @interval * o.number - 1, @startdate) WeekEnd,
        sum(d.DPT) DPT
    from yourtable d
    inner join
        (select ROW_NUMBER() over (order by object_id) as number from sys.all_objects) as o
    on d.FLIGHT_DATE >= dateadd(dd, @interval * (o.number - 1), @startdate)
    and d.FLIGHT_DATE < dateadd(dd, @interval * o.number, @startdate)
    group by o.number
    order by dateadd(dd, @interval * (o.number - 1), @startdate)
    
    0 讨论(0)
提交回复
热议问题