我有一个动态数据透视查询,我想转向businessaccountnumber,我知道它存在于transaction_table中,但它一直返回“无效的列名'bizi'。” - 对于第1行。
DECLARE @Output nvarchar(max) = N''
DECLARE @PivotList varchar(max)
SELECT
@PivotList = COALESCE(@PivotList + ', ', N'') + N'[' + bizid + N']'
FROM (SELECT DISTINCT
BusinessAccountNumber [bizid]
FROM transaction_table
WHERE postingdate BETWEEN '1/01/2015' AND '2/01/2015'
) AS CustProds;
SET @Output = 'SELECT [bizName],[bizi]
, ' + @PivotList + '
FROM ( select businessname as [bizName],businessaccountnumber as [bizi],
sum((Transactionamount*(-1))) as [Transactionamount]
FROM transaction_table
WHERE postingdate between ''1/01/2015'' and ''2/01/2015''
GROUP BY businessaccountnumber,businessname) as P
PIVOT ( SUM(Transactionamount) FOR P.bizi IN (' + @PivotList + ') ) AS PVT'
EXEC sp_executesql @Output;
编辑:感谢Backs指出我的错误,但现在我遇到了一个新错误。
我正在寻找的输出是:
Date | bizid12| bizid13| bizid14...
01/01/2015| $1 | $3 | $56
01/02/2015| $12 | $34 | $3
.....
DECLARE @Output nvarchar(max) = N''
DECLARE @PivotList varchar(max)
SELECT
@PivotList = COALESCE(@PivotList + ', ', N'') + N'[' + bizid + N']'
FROM (SELECT DISTINCT
BusinessAccountNumber [bizid]
FROM transaction_table
WHERE postingdate BETWEEN '1/01/2015' AND '2/01/2015'
) AS CustProds;
SET @Output = 'SELECT [sp_date]
, ' + @PivotList + '
FROM ( select Convert(varchar,postingdate,101) as [sp_date]
,businessaccountnumber as [bizi],
sum((Transactionamount*(-1))) as [Transactionamount]
FROM transaction_table
WHERE postingdate between ''1/01/2015'' and ''2/01/2015''
GROUP BY businessaccountnumber) as P
PIVOT ( SUM(Transactionamount) FOR P.bizi IN (' + @PivotList + ') ) AS PVT'
EXEC sp_executesql @Output;
现在出现错误:
Msg 8180,Level 16,State 1,Line 1
声明无法准备。Msg 102,Level 15,State 1,Line 1
'Qry12090'附近的语法不正确。Msg 1056,Level 15,State 1,Line 1
选择列表中的元素数量超过允许的最大数量4096个元素。
答案 0 :(得分:1)
您无法在PIVOT SELECT [bizName],[bizi]
中使用它在查询FOR P.bizi IN
中选择bizi。从select语句中删除[bizi]