Date ranges in T/SQL

前端 未结 4 973
北荒
北荒 2021-01-15 06:44

For a current project I am working I need to return an aggregate report based on date ranges.

I have 3 types of reports, yearly, monthly and daily.

To assis

4条回答
  •  难免孤独
    2021-01-15 07:12

    There are quite a few tricks in here, hope you find it useful

    create function dbo.fnGetDateRanges
    (
        @type char(1),
        @start datetime,
        @finish datetime
    )
    returns @ranges table(start datetime, finish datetime)
    as 
    begin
    
        declare @from datetime 
        declare @to datetime 
        set @from = @start 
    
        if @type = 'd'
        begin 
            set @to = dateadd(day, 1,
                    convert
                    (   datetime,
                        cast(DatePart(d,@start) as varchar) + '/' + cast(DatePart(m,@start) as varchar) + '/' + cast(DatePart(yy,@start) as varchar),
                        103
                    )
                )
        end
    
        if @type = 'm'
        begin
            set @to = dateadd(month, 1, 
                convert
                (   
                    datetime,
                    '1/' + cast(DatePart(m,@start) as varchar) + '/' + cast(DatePart(yy,@start) as varchar),
                    103
                )
            )
        end 
    
        if @type = 'y'
        begin
            set @to = dateadd(year, 1, 
                convert
                (   
                    datetime,
                    '1/1/' + cast(DatePart(yy,@start) as varchar),
                    103
                )
            )
        end 
    
        while @to < @finish
        begin 
            insert @ranges values (@from, @to)
            set @from = @to 
            if @type = 'd'
                set @to = dateadd(day, 1, @to)
            if @type = 'm'
                set @to = dateadd(month, 1, @to)
            if @type = 'y'
                set @to = dateadd(year, 1, @to)
        end
    
        insert @ranges values (@from, @finish)
    
        return 
    end
    

提交回复
热议问题