SQL Find missing date ranges

前端 未结 2 1438
情深已故
情深已故 2021-01-03 11:23

I have a table that holds all the days/months of the year

E.G.

Day      Month
1         9
2         9
3         9
4         9
5         9
6         9         


        
相关标签:
2条回答
  • 2021-01-03 11:49

    You can use CTE and write a query as:

    declare @StartDate DATE, @EndDate DATE
    set @StartDate = '2013-09-01';
    set @EndDate = '2013-09-30';
    
      WITH DateRange(Date) AS
         (
             SELECT
                 @StartDate Date
             UNION ALL
             SELECT
                 DATEADD(day, 1, Date) Date
             FROM
                 DateRange
             WHERE
                 Date < @EndDate
         )
    
         SELECT 'webshop',Date 
         FROM DateRange
         EXCEPT 
         SELECT DataSet,DateRange
         FROM ImportedDateRange
         WHERE DataSet='webshop'
         --You could remove Maximum Recursion level constraint by specifying a MaxRecusion of zero
         OPTION (MaxRecursion 10000);
    
    0 讨论(0)
  • 2021-01-03 11:51

    If you main table is

    #Temp(Title varchar(10),DateRange date)
    

    You can do like something like

    CREATE TABLE #ALLDATE(Date1 date)
    DECLARE @startDate DATE='9/1/2013'
    DECLARE @endDate DATE='9/30/2013'
    
    insert into #ALLDATE
    SELECT [Date] = DATEADD(Day,Number,@startDate) 
    FROM  master..spt_values 
    WHERE Type='P'
    AND DATEADD(day,Number,@startDate) <= @endDate
    
    
    select 'webshop',Date1 
    from #ALLDATE
    where Date1 not in 
            (select DateRange from #Temp where Title='webshop' and MONTH(GETDATE())=9)
    
    0 讨论(0)
提交回复
热议问题