I am trying to write a function in mySQL that takes two dates(startDate and endDate) as parameters. It then calculates the days in each month.
The database contains a targetRevenue table that has got the target revenue values for each month and year.
id month year targetRev
25 1 2012 1000.00
26 2 2012 5000.00
27 3 2012 8000.00
The function finds the revenue for a month based on the number of days in it and then returns the total.
Example : startDate : 2012-01-19 endDate : 2012-03-24
Function returns [ targetRev(19 days in Jan) + targetRev(29 days Feb) + targetRev(24days in March)]
I am new to writing functions in mysql , so a little bit of help to get me started would be very useful. Thanks in advance!
If instead of your
monthandyearcolumns, you represented the month of each record in yourtargetRevenuetable by aDATEcolumn containing the first day of each month:You could then obtain the total target revenue for your project (assuming it is inclusive of both start and end date) with:
See it on sqlfiddle.
If you can’t change the schema, you could replace references to
firstwith the value to which that column was updated above.