简体   繁体   中英

How can i use PIVOT table on SQL server with AdventureWorksDW database

I listed total sales quantities of customers but I want to list total sales quantities of customers year by year that using PIVOT table.

There is my SQL Query.

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

How can I change this query? Thank you.

    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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM