Table pivot的Sql错误

时间:2016-10-14 18:11:56

标签: sql-server tsql pivot pivot-table

我正在尝试在sql中实现一个透视表,但它无法正常工作。我目前拥有以下内容:

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;
;

我收到错误:

  

多部分“列名称”标识符无法限制。

如果我删除了选择部分中的列名并改为使用*,我得到:

  

为......

指定了多次“ProductCategoryID”列

我想要的是根据每个CompanyName(在客户中)显示每个ParentProductCategoryName(在vGetAllCategories中)所声明的(以列为单位)的总收入(由SalesOrderDetail表中的lineTotal总和指定) )。如何更好地实现这一目标?感谢。

1 个答案:

答案 0 :(得分:0)

不确定为什么你需要一个CTE ...但是将你的JOINS放在一个派生表中并转而使用派生表。

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