T-SQL Multiple grouping

后端 未结 5 908
野性不改
野性不改 2021-01-13 13:46

I have follwing data :

Product Price   StartDate                   EndDate
Apples  4.9     2010-03-01 00:00:00.000     2010-03-01 00:00:00.000
Apples  4.9           


        
5条回答
  •  终归单人心
    2021-01-13 14:45

    I believe this is the best-performing solution so far:

    WITH Calc AS (
       SELECT *,
          Grp = DateAdd(day, -Row_Number()
             OVER (PARTITION BY Product, Price ORDER BY StartDate), StartDate
          )
       FROM dbo.PriceHistory
    )
    SELECT Product, Price, FromDate = Min(StartDate), ToDate = Max(StartDate)
    FROM Calc
    GROUP BY Product, Price, Grp
    ORDER BY FromDate;
    

    Try this out yourself

提交回复
热议问题