统计代码算法查错,只要是在一年的最后一周统计就出错,其他任何时间段都没问题
glboy 2005-08-24 11:21:39 测试代码:
declare @tb table
(
Client_1RecType varchar(10),
Client_1RecTime varchar(10)
)
insert @tb
select '来访','2005-08-11' union all
select '来访','2005-08-12' union all
select '来访','2005-08-15' union all
select '来访','2005-08-15' union all
select '来电','2005-08-16' union all
select '来访','2005-08-17' union all
select '来访','2005-08-17' union all
select '来电','2005-08-17' union all
select '来电','2005-08-17' union all
select '来电','2005-08-17' union all
select '来访','2005-08-18' union all
select '来访','2005-08-18' union all
select '来访','2005-08-18' union all
select '来电','2005-08-18' union all
select '来访','2005-08-18' union all
select '来访','2005-08-18' union all
select '来电','2005-08-18' union all
select '来电','2005-08-19' union all
select '来电','2005-08-28' union all
select '来电','2005-08-28' union all
select '来电','2005-08-29' union all
select '来电','2005-08-29' union all
select '来电','2005-08-29' union all
select '来电','2005-08-29'
declare @startDate datetime,@endDate datetime
select @startDate='2005-08-11',
@endDate='2005-12-25'
--重点注意:只要@endDate设置为某年最后一周的某个日期就会出问题
declare @weeks table([周数] int)
declare @tmp datetime
set @tmp=@startDate
while datepart(week,@tmp)<=datepart(week,@endDate)
begin
insert @weeks select datepart(week,@tmp)
set @tmp=dateadd(day,7,@tmp)
end
--查询
select [总数量]=isnull(T.[总数量],0),
[周数]= '第'+convert(varchar,W.[周数]-datepart(week,@startDate)+1)+'周'
from @weeks W
left join
(
select
[总数量]=count(1),
[周数]=datepart(week,Client_1RecTime)
from @tb
where Client_1RecTime between @startDate and @endDate
group by datepart(week,Client_1RecTime)
)T on W.[周数]=T.[周数]