I have the following code, which groups some events (YYYY-MM-DD HH:MM:SS) in weeks which are displayed as for example “Y:2010 – Week: 50”.
SELECT DATE_FORMAT(date, 'Y:%X - Week:%V') AS regweek, COUNT(*) as number
it works good, but I would like to return all weeks, even if the ones in which no event is placed.
If no event is registered in the third week, at the moment I get:
week 1: 10
week 2: 1
week 4: 2
I would like to get:
week 1: 10
week 2: 1
week 3: 0
week 4: 2
SQL cannot return rows that don’t exist in some table. To get the effect you want, you will need a table Weeks (WeekNo INT) with one row per possible week of the year (which, IIRC, is either 53 or 54 possible weeks, depending on how you count).
Then, JOIN this table to your regular results with an OUTER JOIN to get the extra weeks added in.
[Update]: Note the user of COUNT(date) rather than COUNT(*). SQL will not include NULL values in the date column when adding up the COUNT. Since the missing weeks will not have any dates in them, this will correctly give you 0 events for those weeks.