Hi anonymous user,
I checked manually with the second output of startdate '2020-08-24' and the total sales could be 37 instead of 60. Please help doublecheck it.
Please refer below query and check whether it is helpful to you. Thanks.
;with cte as
(
SELECT starting_date,Ending_Date,PRODUCT_ID,CODE,SUM(SALES) OVER (PARTITION BY PRODUCT_ID,CODE ORDER BY starting_date DESC ROWS BETWEEN CURRENT ROW AND 7 FOLLOWING) SALES
FROM TEST1 )
SELECT A.starting_date,Ending_Date,PRODUCT_ID,CODE,SALES,start_calculation_date
FROM CTE A
CROSS APPLY (
SELECT x.starting_date AS start_calculation_date
FROM (
SELECT TOP 8 *, ROW_NUMBER() OVER (ORDER BY starting_date DESC) AS RowNumber
FROM Test1
WHERE Product_ID = A.Product_ID AND Code = A.Code AND starting_date <= A.starting_date
) AS x
WHERE x.RowNumber = 8
) AS C
ORDER BY A.starting_date DESC
Output:
starting_date Ending_Date PRODUCT_ID CODE SALES start_calculation_date
2020-08-31 2020-09-06 1 O 45 2020-06-08
2020-08-24 2020-08-30 1 O 37 2020-06-01
2020-08-17 2020-08-23 1 B 195 2020-06-08
Best regards
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.