我的 PIVOT 返回重复行,每行中都有数据透视列值

My PIVOT is returning duplicate rows with pivot column values in each row

我有一个问题我看到其他人也有类似的问题,但这些人的答案似乎并不适用于我的情况。这是我的第一个问题,如果有任何格式问题,请提前原谅我,感谢您提供的任何见解。

我的 #TempTBData 看起来像这样:

InvoiceProductID ContactID ContactName ChargeDescription Amount
191 1832    Gloria Cheung   Cruise Fare 500.00
191 1886    John Novosad    Cruise Fare 500.00
191 2011    Christopher Yong    Cruise Fare 100.00

我的数据透视代码如下所示:

SELECT DISTINCT<br>
      [InvoiceProductID]<br>
      ,[ChargeDescription]<br>
      ,[Christopher Yong],[Gloria Cheung],[John Novosad]<br>
      FROM #TempTBData<br>
          PIVOT(MAX([Amount])<br>
          FOR [ContactName] IN ([Christopher Yong],[Gloria Cheung],[John Novosad])) AS PVTTable

..我的 PIVOT 结果如下所示:

 InvoiceProductID ChargeDescription Christopher Yong Gloria Cheung John Novosad

    191 Cruise Fare NULL    NULL    500.00
    191 Cruise Fare NULL    500.00  NULL
    191 Cruise Fare 100.00  NULL    NULL

..我希望结果是:

InvoiceProductID ChargeDescription Christopher Yong Gloria Cheung John Novosad
191 Cruise Fare 100.00  500.00  500.00

请让我知道我做错了什么。

问题是由您的 table 的字段 ContactID 引起的。使用派生的 table 而不是明确选择数据透视操作所需的字段:

SELECT [InvoiceProductID], [ChargeDescription],
       [Christopher Yong],[Gloria Cheung],[John Novosad]
FROM (
  SELECT [InvoiceProductID], [ContactName], [ChargeDescription], [Amount]
  FROM #TempTBData ) AS src
PIVOT(MAX([Amount])
FOR [ContactName] IN ([Christopher Yong],[Gloria Cheung],[John Novosad])) AS PVTTable

我省略了 DISTINCT,因为在这种情况下它似乎是多余的。

Demo here