Sql Table 数据透视错误

Sql Error with Table pivot

我正在尝试在 sql 中实施旋转 table,但它不起作用。我目前拥有的是:

WITH Pivoted
AS
(
select vg.ParentProductCategoryName, c.CompanyName, sd.LineTotal
FROM SalesLT.Product p join SalesLT.vGetAllCategories vg on p.ProductCategoryID = vg.ProductCategoryID
Join SalesLT.SalesOrderDetail sd on p.ProductID = sd.ProductID
JOIN SalesLT.SalesOrderHeader as soh ON sd.SalesOrderID = soh.SalesOrderID
JOIN SalesLT.Customer AS c ON soh.CustomerID = c.CustomerID
pivot(Sum([LineTotal]) for [ParentProductCategoryName] in (Accessories, Bikes, Clothing, Components)) AS sales
)
select * from Pivoted p;
;

我收到错误:

multi part "Column name" Identifier could not be bounded.

如果我删除了 select 部分中的列名并使用 * 代替,我得到:

The column 'ProductCategoryID' was specified multiple times for...

我想要的是查看每个 ParentProductCategoryName(在 vGetAllCategories 中)的总收入(由 SalesOrderDetail Table 中的 lineTotal 总和指定)到每个 CompanyName(在 Customer 中)。如何更好地实现这一点?谢谢。

不确定你为什么需要一个 CTE。但是把你的 JOINS 放在派生的 table 中,然后转而派生 table。

SELECT  *
FROM    (SELECT vg.ParentProductCategoryName,
                c.CompanyName,
                sd.LineTotal
         FROM   SalesLT.Product p
                JOIN SalesLT.vGetAllCategories vg ON p.ProductCategoryID = vg.ProductCategoryID
                JOIN SalesLT.SalesOrderDetail sd ON p.ProductID = sd.ProductID
                JOIN SalesLT.SalesOrderHeader AS soh ON sd.SalesOrderID = soh.SalesOrderID
                JOIN SalesLT.Customer AS c ON soh.CustomerID = c.CustomerID
        ) t 
PIVOT(  SUM([LineTotal]) 
        FOR [ParentProductCategoryName] IN (Accessories,Bikes,Clothing,Components) ) AS sales

或者您可以将 SUM 聚合与 CASE

一起使用
SELECT  c.CompanyName,
        Accessories = SUM(CASE WHEN vg.ParentProductCategoryName = 'Accessories' THEN sd.LineTotal END),
        Bikes       = SUM(CASE WHEN vg.ParentProductCategoryName = 'Bikes' THEN sd.LineTotal END),
        Clothing    = SUM(CASE WHEN vg.ParentProductCategoryName = 'Clothing' THEN sd.LineTotal END),
        Components  = SUM(CASE WHEN vg.ParentProductCategoryName = 'Components' THEN sd.LineTotal END)
FROM    SalesLT.Product p
        JOIN SalesLT.vGetAllCategories vg ON p.ProductCategoryID = vg.ProductCategoryID
        JOIN SalesLT.SalesOrderDetail sd ON p.ProductID = sd.ProductID
        JOIN SalesLT.SalesOrderHeader AS soh ON sd.SalesOrderID = soh.SalesOrderID
        JOIN SalesLT.Customer AS c ON soh.CustomerID = c.CustomerID
GROUP BY c.CompanyName