T-SQL Multiple grouping

后端 未结 5 911
野性不改
野性不改 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条回答
  •  旧时难觅i
    2021-01-13 14:49

    Here's a suggestion: for each row, you must find the maximum previous date for which the price is different and you Group on that. For example, for any line between 2010-03-11 and 2010-03-16, you must retrieve the date 2010-03-10 because this is the maximum previous date for which the price is different (2.5 versus 4.9). The first row(s) will return a null date but that shouldn't be a problem.

    However, for a very long table, this kind of query could become very slow. Therefore, if you have some speed problem, you should look into the possibility of adding a column and use a cursor to fill it incrementally: you loop through it by date and each time you see a new price, you change its value. The final Grouping is then trivial.

    Here's something:

    Select Product, Price, Min(StartDate) as StartDate, PreviousDate from (
        Select product, price, StartDate, (Select max (StartDate) from table_2 t3 where t3.price <> t2.price and t3.StartDate < t2.StartDate and t3.Product = t2.Product) as previousDate
        from table_2 t2) SQ
    
    Group by Product, Price, PreviousDate
    Order by PreviousDate
    

提交回复
热议问题