2011-12-22 100 views
0

我有一个查询,其中绘制了当前以及上个月的男性承诺的销售数量,我想知道是否有效地执行此操作方式,因为它看起来是重复的,如果我得到一年的报告,那么查询将会非常长。如果我能以任何方式改善这个查询,请咨询一下,我正在考虑性能改进或甚至是代码缩减。谢谢。SQL Server +获取当前和上个月的销售查询

Declare @CurrentMonth varchar(20) 
Declare @PreviousMonth varchar(20) 

Set @CurrentMonth = 
( 
select count(*) from transact t 
join card c 
on (t.cardno = c.cardno) 
join member m 
on (c.Memberid = m.id) 

     where mode ='1' 
     and voidby is null 
     and gender='M' 
     and month(transactdate) = month(getdate())    
) 

Set @PreviousMonth = 
(
select count(*) from transact t 
join card c 
on (t.cardno = c.cardno) 
join member m 
on (c.Memberid = m.id) 

     where mode='1' 
     and voidby is null 
     and gender='M' 
     and month(transactdate) = month(dateadd(month, -1, (getdate()))) 

) 

select @currentMonth, @PreviousMonth 

回答

0

请用以前的版本检查结果。非常重要的是,如果存在transactdate,可以使用索引。

declare @CurMonth int 
declare @PrevMonth int 

select @PrevMonth = sum(
     case 
     when transactdate < select dateadd(mm, datediff(mm, 0, getdate()), 0) 
     then 1 else 0 end 
    ), 

    @CurMonth = sum(
     case 
     when transactdate > select dateadd(mm, datediff(mm, 0, getdate()), 0) 
     then 1 else 0 end 
    ) 
from transact t 
join card c on t.cardno = c.cardno 
join member m on c.Memberid = m.id 
where mode ='1' 
and voidby is null 
and gender='M' 
and transactdate >= dateadd(mm, datediff(mm, 0, getdate()) - 1, 0) 
    and transactdate < dateadd(mm, datediff(mm, 0, getdate()) + 1, 0)