Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Count number of days between end of one date range and start of next date range

Posted on 2010-09-01
8
Medium Priority
?
303 Views
Last Modified: 2012-06-27
I am stuck on a query that will calculate the number of days between the end of one date range and the start of the next date range for the same ID (IDs with multiple date ranges).  One ID maybe have one or more date ranges associated with it.

My data looks like this:

ID         Start_Date        End_Date    
1          2009-01-01        2009-03-31
1          2009-05-15        2009-06-30
2          2009-07-01        2009-08-31
2          2009-10-01        2009-12-15
2          2010-01-01        2010-03-31
3          2009-08-01        2009-09-30
4          2009-03-01        2009-03-31
4          2009-04-15        2009-05-31
5          2009-04-01        2009-04-30

I would like the output to add a "Days_Between" field and  look something like this

ID         Start_Date        End_Date      Days_Between  
1          2009-01-01        2009-03-31               0
1          2009-05-15        2009-06-30              45
2          2009-07-01        2009-08-31               0
2          2009-10-01        2009-12-15              30
2          2010-01-01        2010-03-31              16
3          2009-08-01        2009-09-30               0
4          2009-03-01        2009-03-31               0
4          2009-04-15        2009-05-31              15
5          2009-04-01        2009-04-30               0

Single IDs would be assigned 0 as would the first record in a series of like IDs.
Any assistance is appreciated.
Thank you.
0
Comment
Question by:c4e41961
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 6

Accepted Solution

by:
LCSandman8301 earned 2000 total points
ID: 33578291
maybe some toying around with the rank function can help you out. something like this:
select b.id, b.dtstart, b.dtend, isnull(datediff(d, b.dtend,a.dtstart),0)
from (
select rank () over(partition by id order by dtstart) as [rank], id, dtstart, dtend
from testdaterange
) b
left outer join 
(
	select rank () over(partition by id order by dtstart) -1 as [rank], id, dtstart, dtend
	from testdaterange	
) a on b.id = a.id and b.[rank] = a.[rank]

Open in new window

0
 
LVL 41

Expert Comment

by:ralmada
ID: 33578293
something like this?
select *, case when rn <> 1 then datediff(d, start_date, end_date) else 0 end as days_between from 
(
select *, row_number() over (partition by ID order by start_date) rn from yourtable
) a

Open in new window

0
 
LVL 3

Expert Comment

by:aqif_g
ID: 33578350
1          2009-01-01        2009-03-31               0
1          2009-05-15        2009-06-30              45

For me, your concept of id's is totally wrong.

ID is a key to identify a single record uniquely.

First, user keys like,
ID         Start_Date        End_Date      Days_Between  
1          2009-01-01        2009-03-31               0
2          2009-05-15        2009-06-30              45
3          2009-07-01        2009-08-31               0
4          2009-10-01        2009-12-15              30
5          2010-01-01        2010-03-31              16
6          2009-08-01        2009-09-30               0
7          2009-03-01        2009-03-31               0
8          2009-04-15        2009-05-31              15
9          2009-04-01        2009-04-30               0

Now,

to handle dates, there are two ways to handle them.

1 - at mySQL level ( in queries )
2 - at Programming level

I usually handle dates at programming level.


You can pick any two consecutive  data entries like,

(I will use PHP way of declaring variables.)

$id = 3; (or any value)

$nxt = $id + 1;

select * from table where id >= $id AND id<=$nxt;

Now,

two records will gets selected. 1 - with id = $id and other will nbe with id = ($id + 1), that is very next record.

Now,

Subtract End date date of second record date from Start date of first one. What you will get by subtracting (end date of 1st from start date of 2nd record)?

It totally depends upon your knowledge of programming language and how you perform date manipulation.

I  hate handling dates. I usually save dates as STRING hen in PHP I read date (string) from database then I use strtodate() to convert it into int date that is count of seconds from 1971(i guess, donot know exact count). Means thats a big integer value in seconds.

To perform this task in PHP,

1- Before saving new Entry. I would have checked if any previous entry in DB exists. if YES, then read that entry date.
2- convert that entry into integers using strtodate()
3- subtract that date from current entry date. (This will gives me time difference in seconds and I can change it into hours by diving by 3600 and into days by diving by (3600 * 24 ))
4- Then sving the results ;)



regards,
aqif



0
Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

 

Author Closing Comment

by:c4e41961
ID: 33578903
lsandman8301 - your solution was what I was looking for. Thank you for your assistance!

ralmada - your solution returned the number of day between the start and end of the date range on each row,  Maybe I applied your solution incorrectly.

agif_g - I am not a programmer so your solution was not helpful. Also my example field name ID was poorly chosen - that is not, of course, the real field name.  Sorry if that distracted you.

Thank you for your responses.  
0
 
LVL 6

Expert Comment

by:LCSandman8301
ID: 33579076
glad i could help
0
 
LVL 41

Expert Comment

by:ralmada
ID: 33579186
This is what you posterd
1          2009-01-01        2009-03-31               0
1          2009-05-15        2009-06-30              45
from 2009-01-01 to 2009-06-30 there are no 45 days. the 45 days is for the second row. That's why I've posted that solution. You should be more specific when posting.
 
0
 

Author Comment

by:c4e41961
ID: 33579241
"a query that will calculate the number of days between the end of one date range and the start of the next date range for the same ID (IDs with multiple date ranges).  One ID maybe have one or more date ranges associated with it."

I thought I was specific in the narrative description of my problem (see above). Perhaps you could provide a suggestion on how I might of been clearer so I will not make this mistake again.  Thank you for your response.
0
 
LVL 41

Expert Comment

by:ralmada
ID: 33587621
Like I said if you put an example it should match what you are writing. It's common sense only.
0

Featured Post

The Eight Noble Truths of Backup and Recovery

How can IT departments tackle the challenges of a Big Data world? This white paper provides a roadmap to success and helps companies ensure that all their data is safe and secure, no matter if it resides on-premise with physical or virtual machines or in the cloud.

Question has a verified solution.

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

If you having speed problem in loading SQL Server Management Studio, try to uncheck these options in your internet browser (IE -> Internet Options / Advanced / Security):    . Check for publisher's certificate revocation    . Check for server ce…
In this article I will describe the Backup & Restore method as one possible migration process and I will add the extra tasks needed for an upgrade when and where is applied so it will cover all.
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

715 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