2014-01-11 186 views
0

我在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 

有一種方法可以做到這一點,而無需創建臨時表?

+1

這就是所謂的'pivot'。在這裏瞭解它(http://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx)。 –

回答

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 
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 
相關問題