我正在制作一份滚动 36个月的销售历史报告。
我现在有什么:
select
"ItemTable"."ItemNum"
, [1] MM01
, [2] MM02
, [3] MM03
, ...
from (
select
"ItemTable"."ItemNum"
, DateDiff(m, "SalesTable"."SalesDate", GetDate()) months_ago
, "SalesTable"."SalesQty" - "SalesTable"."ReturnsQty" NetQty
from your_table
) as source
pivot
(
sum(NetQty) For months_ago in ([1], [2], [3], ...)
) as PivotTable
以下是比较我的(与上面的代码)和我想要的内容的图片:
如何更改此内容以获得我想要的内容?
答案 0 :(得分:0)
您似乎使用datediff来获取自销售日期以来的月数,但您可以在销售日期列中执行动态调整。这是代码:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF(
(SELECT distinct ',['+datename(mm,SalesTable.SalesDate)+' of '+datename(year,SalesTable.SalesDate)+']' AS months_ago
FROM your_table
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ItemNum, ' + @cols + '
from ( select
ItemTable.ItemNum,
datename(mm,SalesTable.SalesDate)+'' of ''+datename(year,SalesTable.SalesDate)AS months_ago, SalesTable.SalesQty - SalesTable.ReturnsQty AS NetQty
from your_table
) as source
pivot
(
sum(NetQty) For months_ago in (' + @cols + ')
) as PivotTable'
execute sp_executesql @query;