【问题标题】:How can i use PIVOT table on SQL server with AdventureWorksDW database我如何在带有 AdventureWorksDW 数据库的 SQL 服务器上使用 PIVOT 表
【发布时间】:2014-04-07 05:06:23
【问题描述】:

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

如何更改此查询?谢谢。

【问题讨论】:

    标签: sql tsql pivot pivot-table


    【解决方案1】:
        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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多