在 SQL Server 2008 中旋转

Pivoting in SQL Server 2008

这是我的 SQL 旋转脚本

DECLARE @CanvassQuery AS NVARCHAR(MAX)
DECLARE @SupplierName AS NVARCHAR(MAX)

SELECT 
    @SupplierName= ISNULL(@SupplierName + ',','') + QUOTENAME(SupplierName)
FROM 
    (SELECT DISTINCT SupplierName 
     FROM dpiItemCS_Detailed) AS Supplier

SET @CanvassQuery =  N'SELECT ItemDescription, ' + @SupplierName + '
                       FROM dpiItemCS_Detailed
                       PIVOT(SUM(UnitCost) FOR SupplierName IN (' + @SupplierName + '))  AS CanvassTable'

EXEC sp_executesql @CanvassQuery

输出为

+-------------+-----------+------------+-----------+
| Description | Supplier1 | Supplier2  | Supplier3 |
+-------------+-----------+------------+-----------+
| Item 1      | 28.25     | null       | null      |
| Item 1      | null      | 28.50      | null      |
| Item 1      | null      | null       | 28.75     |
+-------------+-----------+------------+-----------+

我希望我的输出是

+-------------+-----------+-----------+-----------+
| Description | Supplier1 | Supplier2 | Supplier3 |
+-------------+-----------+-----------+-----------+
| Item 1      | 28.25     | 28.50     | 28.75     |
+-------------+-----------+-----------+-----------+

旋转以获得此输出的正确 SQL 语句是什么?

没有看到您的 table 结构,我猜测您在 dpiItemCS_Detailed 中有一些唯一的列(可能是 ID 列),在对 PIVOT 进行分组时使用。为了解决这个问题,您需要在 PIVOT 代码中使用子查询。代码应该是:

DECLARE @CanvassQuery AS NVARCHAR(MAX)
DECLARE @SupplierName AS NVARCHAR(MAX)

SELECT 
    @SupplierName= ISNULL(@SupplierName + ',','') + QUOTENAME(SupplierName)
FROM 
    (SELECT DISTINCT SupplierName 
     FROM dpiItemCS_Detailed) AS Supplier

SET @CanvassQuery =  N'SELECT ItemDescription, ' + @SupplierName + '
                       FROM
                       (
                         SELECT ItemDescription, UnitCost, SupplierName
                         FROM dpiItemCS_Detailed
                       ) d
                       PIVOT(SUM(UnitCost) 
                       FOR SupplierName IN (' + @SupplierName + '))  AS CanvassTable'

EXEC sp_executesql @CanvassQuery

当您使用 PIVOT 时,您只想在数据集中包含最终 select 列表和数据透视聚合所需的列 - 包含其他列可能会扭曲您的结果。