以以下示例数据为例:
Payroll Forname Surname Month Year Amount
0000001 James Bond 3 2011 144.00
0000001 James Bond 6 2012 672.00
0000001 James Bond 7 2012 240.00
0000001 James Bond 8 2012 1744.50
0000002 Elvis Presley 3 2011 1491.00
0000002 Elvis Presley 6 2012 189.00
0000002 Elvis Presley 7 2012 1816.50
0000002 Elvis Presley 8 2012 1383.00
我将如何在年 + 月(例如:201210)上对此进行 PIVOT,但将工资单、姓名和姓氏保留为单独的列,例如,上面将变为:
Payroll Forename Surname 201103 201206 201207 201208
0000001 James Bond 144.00 672.00 240.00 1744.50
0000002 Elvis Presley 1491.00 189.00 1816.50 1383.00
我假设因为年份 + 月份名称可以更改,所以我将需要使用动态 SQL + PIVOT - 我试了一下,但甚至无法解析代码,没关系运行 - 任何帮助将不胜感激!
编辑:到目前为止我有什么:
INSERT INTO #tbl_RawDateBuffer
( PayrollNumber ,
Surname ,
Forename ,
[Month] ,
[Year] ,
AmountPayable
)
SELECT PayrollNumber ,
Surname ,
Forename ,
[Month] ,
[Year] ,
AmountPayable
FROM RawData
WHERE [Max] > 1500
DECLARE @Columns AS NVARCHAR(MAX)
DECLARE @StrSQL AS NVARCHAR(MAX)
SET @Columns = STUFF((SELECT DISTINCT
',' + QUOTENAME(CONVERT(VARCHAR(4), c.[Year]) + RIGHT('00' + CONVERT(VARCHAR(2), c.[Month]), 2))
FROM #tbl_RawDateBuffer c
FOR XML PATH('') ,
TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
SET @StrSQL = 'SELECT PayrollNumber, ' + @Columns + ' from
(
select PayrollNumber
, CONVERT(VARCHAR(4), [Year]) + RIGHT(''00'' + CONVERT(VARCHAR(2), [Month]), 2) dt
from #tbl_RawDateBuffer
) x
pivot
(
sum(AmountPayable)
for dt in (' + @Columns + ')
) p '
EXECUTE(@StrSQL)
DROP TABLE #tbl_RawDateBuffer