2014-05-18 97 views
0

我有這個查詢可以找出每年每月的物品數量。但我期待爲累計計算結果,優化查詢針對累計結果優化查詢

SELECT 
COUNT(ITM.ID) AS ItemCount, 
Month(ITM.ItemProcureDate), 
Year(ITM.ItemProcureDate) 
    FROM 
    Rpt_Item ITM 
    WHERE 
    ITM.ItemProcureDate IS NOT NULL  
    AND 
    ITM.ItemStatusID = 2   --  Item sold, Item Rejected 
    AND 
    ITM.ItemProcureDate >= CONVERT(DATETIME,'02/01/2014',1) [email protected]_Date 
    AND 
    ITM.ItemProcureDate <= CONVERT(DATETIME,'04/12/2014',1) [email protected]_Date 
    GROUP BY 
    Month(ITM.ItemProcureDate), 
    Year(ITM.ItemProcureDate) 

查詢結果應該是這樣的:

Item sold In month  2 
Item Sold Till Month  2 
Item Rejected   1  
Item Rejected Till Month 1 
Year    2014 
Month    Feb 
Last Date of Month  02/28/2014 

----------------------------------------------- 
Item sold In month  2 
Item Sold Till Month  4 
Item Rejected   1  
Item Rejected Till Month   2 
Year    2014 
Month    March 
LastDate of Month  03/31/2014 

----------------------------------------------- 
Item sold In month  2 
Item Sold Till Month  6 
Item Rejected   1  
Item Rejected Till Month 3 
Year    2014 
Month    April 
Last Date of Month  04/30/2014 

我必須找出Item_Sold,Item_Rejected,Item_Added爲過去三個月,每一個下個月它應該是累積的所有前幾個月的Item_Sold,Item_Rejected,Item_Added

+2

您的查詢沒有意義。它使用不在'from'子句中的表別名,如'RSK'和'IA'。 –

+0

銷售/拒絕的邏輯是什麼?總之,如果行和列將被交換,每月一行,表示層留給程序或報表 – Serpiton

+0

您想要爲您生成結果的查詢 未優化主版本查詢 它是不同的一個 –

回答

0

在SQL Server 2008中,可以使用相關子查詢或使用非等值鏈接來執行此操作。 SQL Server 2012支持累計求和功能。這裏是一個辦法與相關子查詢做到這一點:

with ym as (
     SELECT COUNT(ITM.ID) AS ItemCount, 
      Month(ITM.ItemProcureDate) as mon, Year(ITM.ItemProcureDate) as yr, 
      Month(ITM.ItemProcureDate) + 100*Year(ITM.ItemProcureDate) as yyyymm 
     FROM Rpt_Item ITM 
     WHERE ITM.ItemProcureDate IS NOT NULL AND 
      ITM.ItemStatusID = 2 AND 
      ITM.ItemProcureDate >= CONVERT(DATETIME,'02/01/2014',1) AND 
      ITM.ItemProcureDate <= CONVERT(DATETIME,'04/12/2014',1) 
     GROUP BY Month(ITM.ItemProcureDate), Year(ITM.ItemProcureDate) 
    ) 
select ym.*, 
     (select sum(ItemCount) 
     from ym ym2 
     where ym.yyyymm <= ym.yyyy.mm 
     ) as cumsum 
from ym; 

需要注意的是,這把年,月入YYYYMM格式。這只是一種方便,所以在時間比較上只使用一列。

此外,如果ITM表格確實很大或是一個視圖,那麼這可能表現得不盡人意。如果性能問題,請使用臨時表而不是CTE。 (SQL Server往往不實現CTE,所以它很可能會運行代碼兩次。)

+0

謝謝戈登,讓我試試你的查詢。 –