T-Sql - Pivot Error
I have the following code in a T-Sql query, I am getting the following error message and I am not really sure what is causing the error. I am writing the Pivot statement to be dynamic b/c I do not know the columns that will be returned.
Error Message: Msg 8156, Level 16, State 1, Line 9 The column 'Title - Endorsement Fee / END8' was specified multiple times for 'PivotTable'.
The Temp Table #FeeTotals has 3 columns 1) dwordrkey (unique id key), 2) Desc_Cd: description of the charge, 3) Total: a money column
DECLARE @PivotColumnHeaders VARCHAR(MAX)
SELECT @PivotColumnHeaders =
COALESCE(
开发者_JS百科 @PivotColumnHeaders + ',[' + cast(Desc_Cd as varchar) + ']',
'[' + cast(Desc_cd as varchar)+ ']'
)
From #FeeTotals
DECLARE @PivotTableSQL NVARCHAR(MAX)
SET @PivotTableSQL = N'
Select *
From #FeeTotals
PIVOT
(
Sum(Total)
For Desc_Cd In (' + @PivotColumnHeaders + ')
)
As PivotTable'
Execute(@PivotTableSQL)
You will need to select DISTINCT
values of Desc_Cd From #FeeTotals when creating the headers. It must be in there twice. Also use the QuoteName
function so your code deals with any Desc_Cd
values that contain the ]
character correctly.
DECLARE @PivotColumnHeaders NVARCHAR(MAX)
SELECT @PivotColumnHeaders =
COALESCE(@PivotColumnHeaders + ',' + Desc_Cd, Desc_Cd)
FROM(
SELECT DISTINCT QUOTENAME(Desc_Cd) AS Desc_Cd
FROM #FeeTotals
) F
精彩评论