Solved

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

Posted on 2010-09-01
8
294 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
  • 3
  • 2
  • 2
  • +1
8 Comments
 
LVL 6

Accepted Solution

by:
LCSandman8301 earned 500 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
 

Author Closing Comment

by:c4e41961
Comment Utility
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
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 6

Expert Comment

by:LCSandman8301
Comment Utility
glad i could help
0
 
LVL 41

Expert Comment

by:ralmada
Comment Utility
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
Comment Utility
"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
Comment Utility
Like I said if you put an example it should match what you are writing. It's common sense only.
0

Featured Post

Free Gift Card with Acronis Backup Purchase!

Backup any data in any location: local and remote systems, physical and virtual servers, private and public clouds, Macs and PCs, tablets and mobile devices, & more! For limited time only, buy any Acronis backup products and get a FREE Amazon/Best Buy gift card worth up to $200!

Join & Write a Comment

I've encountered valid database schemas that do not have a primary key.  For example, I use LogParser from Microsoft to push IIS logs into a SQL database table for processing and analysis.  However, occasionally due to user error or a scheduled task…
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.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

771 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now