1

I use mySql 5 and IIS.
I have products, that have a start date field and an end date field.

I need to run a query that will take user entered Start and End dates, and output the number of days that the product ran within the date range.

Example:

Offer1 - July 1 2011 thru July 31 2011
Query - July 1 2011 thru Sept 15 2011

Results = 31

Example:
Offer1 - July 1 2011 thru July 31 2011
Query - July 1 2011 thru July 15 2011

Results = 15

1 Answer 1

4

If your products have a start_date and an end_date and your query has a qstart_date and a qend_date, then we want the number of days between:

GREATEST(start_date, qstart_date)

and

LEAST(end_date,qend_date)

. In MySQL I think this looks like

1 + DATEDIFF ( 'd' , GREATEST(start_date, qstart_date) , LEAST(end_date,qend_date) ) 

And you'll want to ignore negative numbers, replacing them with "0".

Sign up to request clarification or add additional context in comments.

3 Comments

+1: Could also wrap the DATEDIFF in ABS if the start & end get reversed.
@Chris: You also need to add +1 to this result. As it is, you'll get 31-1 = 30
@OMG Ponies We can't use ABS because then we will mess up sometimes and think that there were some overlaps. Negative numbers here mean "nope, the date ranges didn't overlap; they missed by this much."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.