2016-10-14 172 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