且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

统计时间段内周分类SQL语句

更新时间:2022-10-03 18:27:23

统计时间段内周分类SQL语句
declare @datefrom as datetime,@dateto as datetime

set @datefrom='2015-04-12'
set @dateto='2015-08-13'

declare @table as table(dweek int,fdate datetime,tdate datetime)
declare @yearfrom as int,@monthfrom as int,@dayfrom as int
declare @yearto as int,@monthto as int,@dayto as int
set @yearfrom=year(@datefrom)
set @monthfrom=month(@datefrom)
set @dayfrom=day(@datefrom)
set @yearto=year(@dateto)
set @monthto=month(@dateto)
set @dayto=day(@dateto)

declare @flag as int
set @flag=1




if(@flag=1)
begin
    declare @firstDay as datetime, @currentDay as datetime,@monthdays as int
    declare @curyear as int,@curmonth as int,@curday as int,@dweek as int,@firstflag int
    set @curyear=@yearfrom
    set @curmonth=@monthfrom
    set @curday=@dayfrom

    set @firstflag=0
    set @currentDay= str(@curyear) +'-'+str(@curmonth) +'-'+str(@curday)
    set @dweek=1
    while(@dateto>=@currentDay)
    begin
        set @firstDay= str(@curyear) +'-'+str(@curmonth) +'-01'
        set @monthdays= day(dateadd(d,-day(@firstDay),dateadd(m,1,@firstDay)))
        while(@monthdays>=@curday )
        begin
            set @currentDay= str(@curyear) +'-'+str(@curmonth) +'-'+str(@curday)
            set @curday=@curday+1
            
            if datepart(weekday,@currentDay)=1 and  @dateto>=@currentDay
            begin
                if(@firstflag=1)
                    insert into @table(dweek,fdate,tdate)
                    select @dweek,dateadd(day,-6,@currentDay),@currentDay
                else
                    insert into @table(dweek,fdate,tdate)
                    select @dweek,@datefrom,@currentDay
                
                set @dweek=@dweek+1
                set @firstflag=1
            end
        end
        set @curday=1
        if(@curmonth=12) 
        begin
            set @curmonth=1
            set @curyear=@curyear+1
        end
        else
        begin
            set @curmonth=@curmonth+1
        end
    end
end

if(datepart(weekday,@dateto)>1)
begin
                    insert into @table(dweek,fdate,tdate)
                    select @dweek,dateadd(day,2-datepart(weekday,@dateto),@dateto),@dateto
end

select *from @table
统计时间段内周分类SQL语句