T-Sql - 透视错误
我在 T-Sql 查询中有以下代码,收到以下错误消息,但我不太确定导致错误的原因。我正在将 Pivot 语句编写为动态的,因为我不知道将返回的列。
错误消息:消息 8156,级别 16,状态 1,第 9 行 为“数据透视表”多次指定了“标题 - 认可费/END8”列。
临时表 #FeeTotals 有 3 列 1) dwordrkey(唯一 id 键),2) Desc_Cd:费用描述,3) Total:货币列
DECLARE @PivotColumnHeaders VARCHAR(MAX)
SELECT @PivotColumnHeaders =
COALESCE(
@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)
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(
@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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建标头时,您需要从#FeeTotals 中选择
DISTINCT
DES_Cd 值。它必须在那里出现两次。还可以使用QuoteName
函数,以便您的代码正确处理包含]
字符的任何Desc_Cd
值。You will need to select
DISTINCT
values of Desc_Cd From #FeeTotals when creating the headers. It must be in there twice. Also use theQuoteName
function so your code deals with anyDesc_Cd
values that contain the]
character correctly.