2009-10-06 80 views
0
select CAST(convert(varchar, a.rechargedate, 112) as datetime)as RechargeDate, 
COUNT(distinct a.mobileno) AS UnitTotal, 
SUM(a.amount) AS AmountTotal 
from recharge a 
where *a.rechargedate BETWEEN '2009-07-01' AND '2009-07-31'* 
group by CAST(convert(varchar, a.rechargedate, 112) as datetime) 
order by a.rechargedate 

上面是我的sql查询。在
((((a.rechargedate BETWEEN '2009-07-01' AND '2009-07-31' )))))
我会改变它通过使用循环。所以如果下次我想改变日期到八月。它会自动循环。我不需要手动键入日期到2009-08-01 ........ 有人可以帮助我吗?告诉我如何制作它?如何为日期制作SQL循环?

回答

0

这一切都取决于你的逻辑,这里有一些选择:

  1. 采取@startDate和@EndDate作为存储过程
  2. ,如果你能在逻辑上打结的日期为当前日期,你可以calculate them参数在基于getdate()的存储(或函数)(将给你当前的日期)
1

不知道这只是一个查询,你正在使用自己来查看数据,或者如果它假设是在sproc中。如果它只是一个实用程序查询,你可以这样做。,

declare @firstofmonth as smalldatetime 
declare @endofmonth as smalldatetime 

--Set the inital month to loop 
set @firstofmonth = '01/01/2009' 
set @endofmonth = '01/31/2009' 

WHILE @firstofmonth >= '09/01/2009' --This would be the condition to end the loop 

Begin 

select CAST(convert(varchar, a.rechargedate, 112) as datetime)as RechargeDate, 
    COUNT(distinct a.mobileno) AS UnitTotal, 
    SUM(a.amount) AS AmountTotal 
From recharge a 
Where a.rechargedate BETWEEN @firstofmonth AND @endofmonth 
group by CAST(convert(varchar, a.rechargedate, 112) as datetime) 
order by a.rechargedate 

SET @firstofmonth = DateAdd(m,1,@firstofmonth) 
SET @endofmonth = DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@firstofmonth())+1,0)) 

End