User347430248 posted
Hi
JagjitSingh,
you had asked," I want to generate query that should calculate Sales Data MTD & YTD."
you can try to refer example below.
declare @Sales table (TDate date, ProductId char(3), SalesAmount int)
insert @Sales
select '2011-01-20', 'P01', 100 union all
select '2011-02-01', 'P02', 200 union all
select '2011-03-12', 'P01', 50 union all
select '2011-03-20', 'P02', 75 union all
select '2011-01-01', 'P02', 120 union all
select '2011-01-18', 'P01', 60 union all
select '2011-02-11', 'P01', 90;
with Sales2011 as (
select M = month(TDate), MonthName = convert(char(3), TDate, 0), * from @Sales where year(TDate) = 2011
), PeriodWise as
(
select M, MonthName, ProductId, MonthTotal = sum(SalesAmount) from Sales2011
group by M, MonthName, ProductId
)
select MonthName, ProductId, MonthTotal, YTD
from PeriodWise a cross apply (
select YTD = sum(b.MonthTotal) from PeriodWise b where a.M >= b.M and a.ProductId = b.ProductId
) x order by ProductId, M
Output:

Reference:
Calculate YTD and MTD by Period
Regards
Deepak