2014-05-18 98 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

谢谢戈登,让我试试你的查询。 –