我在下面有一个查询,其中列出了当前和上个月男性的销售数量,我想知道这样做是否有效,因为它看起来很重复,如果我得到的话报告一年后查询将非常长。如果我能以任何方式改进此查询,请咨询,我正在考虑性能改进甚至代码减少。感谢。
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 :(得分: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)