Hi,
Yes, you are correct. I have updated my output in the question that was posted.
one row makes it not fit since Feb is a short month and the different between 2022-02-13
and 2022-03-14
is only 29 days which mean it should not be reset at 2022-03-14
Anyway, assuming the description is correct and you mean to reset only and always when the difference is 30 days or more, then this is the solution
;With MyCTE as (
SELECT PRODUCT, MyDate, price,
Dif_Days = DATEDIFF(Day,LAG(MyDate) OVER (ORDER BY MyDate), MyDate), --This present the differences in days
DaysDiff = case
when isnull(DATEDIFF(Day,LAG(MyDate) OVER (ORDER BY MyDate), MyDate),0) < 30 then 0
else 1
end
FROM T
),
MyCTE2 as (
select PRODUCT, MyDate, price
, Dif_Days, G = SUM(DaysDiff) OVER (partition by PRODUCT ORDER BY MyDate)
from MyCTE
)
select PRODUCT, MyDate, price
, Total = SUM (price) OVER (partition by PRODUCT, G ORDER BY MyDate ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
, Dif_Days, G
from MyCTE2
I added several more rows to make it more clear how the result behaves, so this is the DDL+DML I used:
USE tempdb
GO
------------------------------------ DDL - should be provided by the OP!
DROP TABLE IF EXISTS T
GO
CREATE TABLE T(PRODUCT VARCHAR(2), MyDate Date, price INT)
GO
------------------------------------ DML - should be provided by the OP!
INSERT T(PRODUCT, MyDate, price)
VALUES
('p1',CONVERT(DATE,'10/1/2022',103),1000),
('p1',CONVERT(DATE,'11/1/2022',103),1000),
('p1',CONVERT(DATE,'15/1/2022',103),1000),
('p1',CONVERT(DATE,'12/2/2022',103),1100),
('p1',CONVERT(DATE,'13/2/2022',103),1100),
('p1',CONVERT(DATE,'14/3/2022',103),1200),
('p1',CONVERT(DATE,'30/4/2022',103),1500),
('p1',CONVERT(DATE,'22/5/2022',103),1500),
('p1',CONVERT(DATE,'30/6/2022',103),1500),
('p1',CONVERT(DATE,'22/7/2022',103),1500),
('p1',CONVERT(DATE,'30/7/2022',103),1500),
('p1',CONVERT(DATE,'30/11/2022',103),1500)
GO
SELECT * FROM T
GO
The result set fits you description