2016-10-14 126 views
0

我想在sql中实现一个枢轴表,但它不工作。我目前有如下:与表枢轴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; 
; 

我得到的错误:

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

如果我在选择部分删除的列名,并用*代替,我得到:

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

我想要的是每个ParentProductCategoryName(在vGetAllCategories中)声明的总收入(由SalesOrderDetail表中的lineTotal的总和指定)每个公司名称(在客户中)。如何更好地实现这一目标?谢谢。

+0

变化'vg.ParentProductCategoryName'为'vg.ParentProductCategoryName作为ParentProductCategoryName'让你的支点识别列您指定,你必须'为[ParentProductCategoryName]',或者适当的别名。 – scsimon

+0

不是问题,没有区别。 – mj1261829

回答

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