如何在AdventureWorksDW数据库的SQL服务器上使用PIVOT表

时间:2014-03-05 08:49:23

标签: sql tsql pivot pivot-table

我列出了客户的总销售数量,但我想列出使用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

如何更改此查询?谢谢。

1 个答案:

答案 0 :(得分: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