declare @sql nvarchar(2048)='
select StockCode
,sum(['+datename(month,dateadd(month,datediff(month,0,current_timestamp)-1,0))+ '-'+ right(cast(year(getdate()) as varchar),2)+']) as ['+datename(month,dateadd(month,datediff(month,0,current_timestamp)-1,0))+ '-'+ right(cast(year(getdate()) as varchar),2)+']
,sum(['+datename(month,dateadd(month,datediff(month,0,current_timestamp),0))+ '-'+ right(cast(year(getdate()) as varchar),2)+']) as ['+datename(month,dateadd(month,datediff(month,0,current_timestamp),0))+ '-'+ right(cast(year(getdate()) as varchar),2)+']
,sum(['+datename(month,dateadd(month,datediff(month,0,current_timestamp)+1,0))+ '-'+ right(cast(year(getdate()) as varchar),2)+']) as ['+datename(month,dateadd(month,datediff(month,0,current_timestamp)+1,0))+ '-'+ right(cast(year(getdate()) as varchar),2)+']
,sum(['+datename(month,dateadd(month,datediff(month,0,current_timestamp)-+2,0))+ '-'+ right(cast(year(getdate()) as varchar),2)+']) as ['+datename(month,dateadd(month,datediff(month,0,current_timestamp)-+2,0))+ '-'+ right(cast(year(getdate()) as varchar),2)+']
from(
select StockCode,dense_rank() over(order by StockCode) as RowNumber
,case
when FDate>=dateadd(month,datediff(month,0,current_timestamp)-1,0)
and FDate<dateadd(month,datediff(month,0,current_timestamp),0)
then sum(Qty)
else 0
end
as ['+datename(month,dateadd(month,datediff(month,0,current_timestamp)-1,0))+ '-'+ right(cast(year(getdate()) as varchar),2)+']
, case when FDate>=dateadd(month,datediff(month,0,current_timestamp),0)
and FDate<dateadd(month,datediff(month,0,current_timestamp)+1,0)
then sum(Qty)
else 0
end
as ['+datename(month,dateadd(month,datediff(month,0,current_timestamp),0))+ '-'+ right(cast(year(getdate()) as varchar),2)+']
, case when FDate>=dateadd(month,datediff(month,0,current_timestamp)+1,0)
and FDate<dateadd(month,datediff(month,0,current_timestamp)+2,0)
then sum(Qty)
else 0
end
as ['+datename(month,dateadd(month,datediff(month,0,current_timestamp)+1,0))+ '-'+ right(cast(year(getdate()) as varchar),2)+']
,case when FDate>=dateadd(month,datediff(month,0,current_timestamp)+2,0)
and FDate<dateadd(month,datediff(month,0,current_timestamp)+3,0)
then sum(Qty)
else 0
end
as ['+datename(month,dateadd(month,datediff(month,0,current_timestamp)-+2,0))+ '-'+ right(cast(year(getdate()) as varchar),2)+']
from [dbo].[Mrp]
group by StockCode,FDate)t
group by StockCode , RowNumber'
execute sp_executesql @sql;