2017-06-16 49 views
0

我正在研究SQL Server 2012.嘗試Pivot表數據。如何針對給定的查詢執行SQL數據透視表?

我曾嘗試下面下面的查詢,

SELECT CategoryName, 1996_Val, 1997_Val 
FROM( 
SELECT 
Categories.CategoryName, 
Sum(CONVERT(money,("Order Details".UnitPrice*Quantity*(1-Discount)/100))*100) AS Sales, 
YEAR(Orders.ShippedDate) AS ShippingYear 
FROM Orders 
INNER JOIN [Order Details] ON Orders.OrderID = [Order Details].OrderID 
INNER JOIN Products ON [Order Details].ProductID = Products.ProductID 
INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID 
WHERE (((Orders.ShippedDate) Between '19960101' And '19971231')) 
GROUP BY Categories.CategoryID, Categories.CategoryName,YEAR(Orders.ShippedDate) 
)p 
PIVOT 
(MAX(Sales) For ShippingYear IN(1996,1997)) AS pvt 
ORDER BY Categories.CategoryID 

,沒有工作。請幫助我...

回答

1

我認爲你得到的關鍵點有點不對。我認爲它應該看起來像這樣:

SELECT 
    * 
FROM 
(
SELECT 
    Categories.CategoryName, 
    YEAR(Orders.ShippedDate) AS ShippingYear, 
    CONVERT(money,([Order Details].UnitPrice*Quantity*(1-Discount)/100))*100 as Sales 
FROM 
    Orders 
INNER JOIN [Order Details] ON Orders.OrderID = [Order Details].OrderID 
INNER JOIN Products ON [Order Details].ProductID = Products.ProductID 
INNER JOIN Categories ON Products.CategoryID = Categories.CategoryID 
WHERE (((Orders.ShippedDate) Between '19960101' And '19971231')) 
) AS SourceTable 
PIVOT 
(
    SUM(Sales) 
    FOR CategoryName IN ([Confections],[Meat/Poultry], 
         [Beverages],[Grains/Cereals],[Seafood]) 
) AS pvt