SQL Server 2008 R2:PIVOT 查询中的列名无效

SQL Server 2008 R2: Invalid column name in PIVOT query

我有一个动态数据透视查询,我想在我知道存在于 transaction_table 中的 businessaccountnumber 上进行数据透视,但它一直返回第 1 行的 "Invalid column name 'bizi'."-。

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|      |      | 
01/02/2015|     |     | 
.....


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
Statement(s) could not be prepared.

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'Qry12090'.

Msg 1056, Level 15, State 1, Line 1
The number of elements in the select list exceeds the maximum allowed number of 4096 elements.

您无法在查询 SELECT [bizName],[bizi] 中 select bizi 在 PIVOT FOR P.bizi IN 中使用它。从 select 语句

中删除 [bizi]