I am trying to summarize records using the following query in MySQL. It works great as long as there is at least one record in each year. If records are missing in years, then the year doesn’t show up. How can I modify this to show each year within my filter?
SELECT SUM( SICK_SIZE + DEAD_SIZE ) AS Cases, DATE_FORMAT( EVENT_DATE, '%Y' ) AS DateYear
FROM report_case_ext
WHERE DATE_FORMAT( EVENT_DATE, '%Y' ) >= DATE_FORMAT( DATE_ADD( CURDATE( ) , INTERVAL -4YEAR ) , '%Y' )
AND DATE_FORMAT( EVENT_DATE, '%Y' ) <= DATE_FORMAT( CURDATE( ) , '%Y' )
GROUP BY DATE_FORMAT( EVENT_DATE, '%Y' )
In MySQL, you can use sqlvariables, join to any other table to simulate row creation — which returns a valid result set of the years you are looking for, then LEFT-JOIN to your other table so you know you’ll always get the years you want…
The inner prequery that uses “report_case_ext” is only used to have a table of at least 5 records to keep the years you want… In this case,
@nYear is initialized to 1 year less than the 4 you were looking for — hence -5
curdate() = 2013 – 5 = 2008.
Then, in the select @nYear := @nYear +1 first time will have the first year become 2009 and complete for 5 years, thus generating a record for 2009, 2010, 2011, 2012 and 2013 (via LIMIT 5)
Now that result (of all years) is LEFT-joined to the report_case_ext table on common years. So, even those that have no dates