2014-03-05 25 views
0

我列出了客戶的總銷售數量,但我想列出使用PIVOT表的年度客戶總銷售數量。我如何在AdventureWorksDW數據庫上使用SQL服務器上的PIVOT表格

有我的SQL查詢。

SELECT FirstName , 
     LastName , 
     EnglishProductName , 
     CASE WHEN CalendarYear = '2001' THEN Quantity 
      ELSE 0 
     END AS '2001 Sales' , 
     CASE WHEN CalendarYear = '2002' THEN Quantity 
      ELSE 0 
     END AS '2002 Sales' , 
     CASE WHEN CalendarYear = '2003' THEN Quantity 
      ELSE 0 
     END AS '2003 Sales' , 
     CASE WHEN CalendarYear = '2004' THEN Quantity 
      ELSE 0 
     END AS '2004 Sales' 
FROM (SELECT CUS.FirstName , 
        CUS.LastName , 
        PROD.EnglishProductName , 
        SUM(SALE.OrderQuantity) Quantity , 
        TAR.CalendarYear 
      FROM  DimProduct AS PROD 
        INNER JOIN FactInternetSales AS SALE ON SALE.ProductKey = PROD.ProductKey 
        INNER JOIN DimTime AS TAR ON TAR.TimeKey = SALE.OrderDateKey 
        INNER JOIN DimCustomer AS CUS ON CUS.CustomerKey = SALE.CustomerKey 
      GROUP BY CUS.FirstName , 
        CUS.LastName , 
        EnglishProductName , 
        CalendarYear 
     ) AS SUB 

如何更改此查詢?謝謝。

回答

0
select FirstName, 
      LastName, 
      EnglishProductName, 
      [2001], 
      [2002], 
      [2003], 
      [2004] from 
    (
    select CUS.FirstName, 
      CUS.LastName, 
      PROD.EnglishProductName, 
      SUM(SALE.OrderQuantity) Quantity, 
      TAR.CalendarYear YIL 
    from DimProduct as PROD 
      inner join FactInternetSales as SALE on SALE.ProductKey = PROD.ProductKey 
      inner join DimTime as TAR on TAR.TimeKey = SALE.OrderDateKey 
      inner join DimCustomer as CUS on CUS.CustomerKey = SALE.CustomerKey 
    group by CUS.FirstName, 
      CUS.LastName, 
      EnglishProductName, 
      CalendarYear 
) as gTablo 
    PIVOT 
    (
    SUM(Quantity) 
    FOR YIL IN ([Name],[2001],[2002],[2003],[2004]) 
    ) 
    as P 
    order by FirstName 
相關問題