查询比较两年销售情况

时间:2014-01-11 18:20:47

标签: sql-server tsql

我在SQL Server中有一个包含以下列的表:

  • 产品
  • 数量

示例:

Year   Month  Product  Qty
2011   1      XYZQW     45

因此在此表中存储了所有产品销售。

我需要构建一个查询来比较一年及其之前的内容来构建此报告:

Year   GEN FEB MAR APR MAY GIU JUL AUG SEP OCT NOV DEC 
-------------------------------------------------------
2011    12  23  56  54  14  11  15  18  89  87  48  98
2012    19  21  55  50  24  10  19  17  88  81  45  90

有一种方法可以在不创建临时表的情况下执行此操作吗?

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT  [Year]  = z.[Year],
        [Gen]   = ISNULL(z.[1], 0),
        [Feb]   = ISNULL(z.[2], 0),
        [Mar]   = ISNULL(z.[3], 0),
        ...
        [Dec]   = ISNULL(z.[12],0)
FROM    ( SELECT x.[Year], x.[Month], x.Qty FROM dbo.MyTable x WHERE x.[Year] IN (2011, 2012) ) y
PIVOT   ( SUM(y.qty) FOR y.[Month] IN  ([1], [2], [3], ..., [12]) ) z

答案 1 :(得分:0)

这很简单,试试这个:

WITH DT(AMonth,AYear,AQty)
     AS (SELECT Month, Year, Qty
         FROM YourTable)
SELECT pvt.*
FROM     DT cte
         PIVOT
         (SUM(AQty)
          FOR AYear IN ( [2011],[2012],[2013],[2014] ) ) AS pvt