Date ranges in T/SQL

前端 未结 4 949
北荒
北荒 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:04

    From a performance standpoint, you will not want to use a function to generate the date ranges. For each evaluation in the query ( @myDate > dbo.MyFunc() ), the function will have to execute fully. Your best bet is to build static numbers table.

    Now on with the numbers tables....

    This is a fast way to create a integers table. (Props to Jeff Moden for the Identity Trick)

     SELECT TOP 1000000
            IDENTITY(INT,1,1) as N
       INTO dbo.NumbersTable
       FROM Master.dbo.SysColumns 
            Master.dbo.SysColumns 
    

    Less than 2 seconds to populate 1000000 numbers in a table.

    Now to address your problem, you will need to use this to build a table of dates. The example below will create a table with the zero hour (12AM) for each day starting from the @startDate

    DECLARE @DaysFromStart int
    DECLARE @StartDate datetime
    SET @StartDate = '10/01/2008'
    
    SET @ DaysFromStart  = (SELECT (DATEDIFF(dd,@StartDate,GETDATE()) + 1))
    
    CREATE TABLE [dbo].[TableOfDates](
        [fld_date] [datetime] NOT NULL,
     CONSTRAINT [PK_TableOfDates] PRIMARY KEY CLUSTERED 
    (
        [fld_date] ASC
    )WITH FILLFACTOR = 99 ON [PRIMARY]
    ) ON [PRIMARY]
    
    
    INSERT INTO
         dbo.TableOfDates
    SELECT 
          DATEADD(dd,nums.n - @DaysFromStart ,CAST(FLOOR(CAST(GETDATE() as FLOAT)) as DateTime)) as FLD_Date
    FROM #NumbersTable nums
    
    SELECT MIN(FLD_Date) FROM dbo.TableOfDates
    SELECT MAX(FLD_Date) FROM dbo.TableOfDates
    

    Now with different combinations of DATEADD/DIFF, you should be able to create the static tables that you will need to do many date range queries efficiently.

提交回复
热议问题