Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Count overlapping days between 2 date ranges

Posted on 2004-10-01
3
Medium Priority
?
2,648 Views
Last Modified: 2012-05-08
Hi,

I'm trying to create a query that counts the overlapping days between 2 date ranges from a view.

For example take this range in the view RESERVATIONS:
startdate | enddate | totaldaycount
2004-01-04 | 2004-01-08 | 4

in the query should look something like this:

SELECT @startdate = '2004-01-02';
SELECT @enddate =  '2004-01-06';
SELECT overlappingdays = ( ...?... ) FROM RESERVATIONS  
  WHERE (startdate BETWEEN @startdate +1 AND @enddate -1)
    OR (enddate BETWEEN @startdate +1 AND @enddate -1)
    OR (startdate <= @startdate AND enddate >= @enddate)

the resulting integers from the following ranges should be:
@startdate | @enddate | @result
2004-01-02 | 2004-01-06 | 2
2004-01-04 | 2004-01-08 | 4
2004-01-06 | 2004-01-10 | 2
2004-01-02 | 2004-01-10 | 4

I don't want to use function (I know how to get the result like that), preferably a pure select query.

Thanks!

Wiebe
0
Comment
Question by:Uritsukidoji
3 Comments
 
LVL 15

Expert Comment

by:justinbillig
ID: 12201532
i dont get what you mean by overlapping days
0
 
LVL 70

Accepted Solution

by:
Scott Pletcher earned 2000 total points
ID: 12201775
Please try this:


SELECT overlappingdays = DATEDIFF(DAY,
      CASE WHEN startDate > @startDate THEN startDate ELSE @startDate END,
      CASE WHEN endDate < @endDate THEN endDate ELSE @endDate END)
FROM ...
0
 
LVL 3

Author Comment

by:Uritsukidoji
ID: 12203654
Scott, it works fine!

Thanks a lot,

Wiebe
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
One of the most important things in an application is the query performance. This article intends to give you good tips to improve the performance of your queries.
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

879 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question