Question

I have a MySQL database with one table that contains a data field and a "period" field, in months - int.

The idea is that the date indicates a due date to begin a project inside my company. And the "period" the period of time it is suppose to take to finish it, in months.

I need to select rows that will impact a given year. So if I am generating a report for 2014, I need to select the rows such: date+period is inside 2014.

It will be easy to do it inside the program, but I am looking for a way to do it in the query - if possible.

So basically I just need a way to sum dates and ints in a query, where the int is the number of months.

Any thoughts?

Was it helpful?

Solution

It's easy to do date arithmetic in MySQL and other RDMS systems. You need all the records in which the start date is not after the year in question OR the end date is not before the year in question. That is this expression:

NOT(YEAR(start_date) > 2014  OR YEAR(start_date + INTERVAL period MONTH) < 2014)  

This logically reduces to

YEAR(start_date) <= 2014 AND YEAR(start_date + INTERVAL period MONTH) >= 2014

So this query will do it.

SELECT whatever, whatever
  FROM project
 WHERE YEAR(start_date) <= 2014
   AND YEAR(start_date + INTERVAL period MONTH) >= 2014
   AND (whatever other selection criteria you have)

This will give all projects that were active during 2014, including those that started before 2014 and those that will still be in progress at the end of that year.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top