我有以下 SQL 查询,其中创建的列乱序,我不太确定如何修复它。
SELECT rhead.rhcust AS [Cust ID], rdetl.rdextp AS [Inv Amt], rhead.rhivdt AS [Inv Date]
INTO #TempTable
FROM rhead
LEFT OUTER JOIN rdetl
ON rhead.rhinvc = rdetl.rdinvc
WHERE rhead.rhivdt >= '01-01-2012' AND rhead.rhivdt <= '12-25-12'
ALTER DATABASE Vista_TM SET COMPATIBILITY_LEVEL = 100
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME('Month'+cast(DATEPART(m, [Inv Date]) as varchar(2)))
from #TempTable
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ,1,1,'')
set @query = 'SELECT [Cust ID],' + @cols + '
from
(
SELECT [Cust ID], [Inv Amt],
''Month''+cast(DATEPART(m, [Inv Date]) as varchar(2)) MonthNo
FROM #TempTable
) x
pivot
(
sum([Inv Amt])
for MonthNo in (' + @cols + ')
) p '
execute(@query)
DROP TABLE #TempTable
我相信它与查询的这一部分有关:
select @cols = STUFF((SELECT distinct ',' + QUOTENAME('Month'+cast(DATEPART(m, [Inv Date]) as varchar(2)))
from #TempTable
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') ,1,1,'')
我确实尝试过弄乱这个主题中发布的答案,但我无法运行查询。我希望有人可以提供帮助。
编辑我刚刚注意到我的行有问题,并且也想按 [Cust ID] 排序。