I am working on a query to get sum of (current + last 2 month) QTY based on a date field in the table.
CREATE table #temp_Sales
( Client varchar(10),
Sale_Month Date,
Qty int)
Insert into #temp_Sales VALUES
( 'AAAA', '2022-06-01', 5 ),
( 'AAAA', '2022-05-01', 10 ),
( 'AAAA', '2022-05-01', 2 ),
( 'AAAA', '2022-04-01', 5 ),
( 'AAAA', '2022-02-01', 15),
( 'BBBB', '2022-05-01', 2 ),
( 'BBBB', '2022-04-01', 4),
( 'BBBB', '2022-03-01', 6 ),
( 'BBBB', '2022-03-01', 10 ),
( 'BBBB', '2022-01-01', 6 ),
( 'BBBB', '2021-10-01', 10),
( 'BBBB', '2021-09-01', 2 ),
( 'BBBB', '2021-11-01', 4 ),
( 'BBBB', '2021-08-01', 6),
( 'BBBB', '2021-07-01', 8 ),
( 'CCCC', '2021-11-01', 2 ),
( 'CCCC', '2021-10-01', 3 ),
( 'CCCC', '2021-09-01', 30 ),
( 'CCCC', '2021-06-01', 4 )
Sample data:
Expected Output:
The Sale_month is not consecutive and same month can appear more than once for a client in the table.
Example : For the Client AAAA and Sale Month 2022-06-01 the qty should include the sum(QTY) of current and last 2 months ( 2022-06-01,2022-05-01 and 2022-04-01) for that client. QTY = 5 + 10 + 2 + 5 = 22
For the client BBBB and Sale month 2022-03-01 . QTY = 6 + 10 + 6 = 22
;With da AS
(SELECT *, DATEADD(MM,-2,Sale_month)as last_two_Months FROM #temp_Sales)
Select Client,Sale_month,Sum(qty) from da
WHERE Sale_month Between last_two_Months and Sale_month
GROUP BY Client,Sale_month
Order by client
Tried the above query. But not working as expected not sure how to group by using last_two_Months and Sale_month. Any help is much appreciated.

