2011-12-22 9 views
0

私は以下のクエリを使用して、現在の月と前月の男性のコミット販売数量を表示します。これは効率的かどうかを確認したい繰り返しているように見えるので、1年間レポートを取得すると、クエリは非常に長くなります。私はこのクエリでどのように改善することができれば助言してください、私はパフォーマンスの改善やコードの削減を検討しています。ありがとう。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) 
関連する問題