Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 views
in Technique[技术] by (71.8m points)

sql server - SQL Find missing date ranges

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
7         9
...       ...

I have a table which shows the date ranges from different datasets

E.G.

 DataSet    DateRange
webshop 2013-09-20
webshop 2013-09-21
webshop 2013-09-22
webshop 2013-09-23
webshop 2013-09-24
webshop 2013-09-25
webshop 2013-09-26
webshop 2013-09-27
webshop 2013-09-28
webshop 2013-09-29
webshop 2013-09-30

How would I compare the two tables to show which days are missing from the DataSet for that particular month

E.G. for my example above where the dataset is webshop it is missing the date range 01/09/2013 - 19/09/2013

Thanks for any help!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...