Home All Groups Group Topic Archive Search About

Advanced query to fetch gaps in date range?

Author
9 Jul 2005 7:15 PM
Mark Findlay
I am attempting to formulate a query that will tell me if there are any
single-day gaps in a series of records in a reservation table:

Here is the reservation table
-----------------------------
id             int
startdate   smalldatetime
enddate    smalldatetime
guestid      int

Assuming the table has the following data:

1,3/3/2005,3/6/2005,222
2,3/9/2005,3/10/2005,222
3,4/1/2005,4/5/2005,222

I wish to be able to query the table to see if there is at least 1 free day
anywhere in the span 3/5/2005 to 3/8/2005, but so far I haven't been able
to. At first I thought I could SUM the number of days that each reservation
record represented (the first record represents 4 days, the 2nd record has 2
days, the 3rd record has 5 days) and then compare that with the span of days
I am searching, but that would not work since the first record actual starts
2 days before my search range so would throw off the calculation.

Any thoughts on how I could write a query that would tell me if there was
any single day free between 3/5/2005 and 3/8/2005 given the data above?

Thanks experts!

Author
9 Jul 2005 7:31 PM
--CELKO--
Build a Calendar table, then use it for this and all of your other
temporal queries.

SELECT C1.cal_date
  FROM Calendars AS C1
WHERE NOT EXISTS
  (SELECT *
      FROM Reservations AS R1
  WHERE C1.cal_date BETWEEN R1.start_date AND R1.end_date);
Author
9 Jul 2005 10:38 PM
Mark Findlay
Great idea! Thanks so much!

Mark

Show quote
"--CELKO--" <jcelko***@earthlink.net> wrote in message
news:1120937507.366118.236250@f14g2000cwb.googlegroups.com...
> Build a Calendar table, then use it for this and all of your other
> temporal queries.
>
> SELECT C1.cal_date
>  FROM Calendars AS C1
> WHERE NOT EXISTS
>  (SELECT *
>      FROM Reservations AS R1
>  WHERE C1.cal_date BETWEEN R1.start_date AND R1.end_date);
>
Author
10 Jul 2005 1:15 AM
--CELKO--
Get a copy of any of my books, which improve your  SQL and my ability
andmy ability to live indoors :)
Author
10 Jul 2005 3:28 AM
Louis Davidson
Shameless, shameless :)

--
----------------------------------------------------------------------------
Louis Davidson - http://spaces.msn.com/members/drsql/
SQL Server MVP


Show quote
"--CELKO--" <jcelko***@earthlink.net> wrote in message
news:1120958124.017777.151700@o13g2000cwo.googlegroups.com...
> Get a copy of any of my books, which improve your  SQL and my ability
> andmy ability to live indoors :)
>

AddThis Social Bookmark Button