I need to display the total number of orders for each year and month. But for several months there is no data, but I want to show this month (with a full zero value). I could create ancillary βmonthsβ with 12 entries for each year, but could there be a way to get a whole series of months without introducing a new table?
Something like:
SELECT [all year-month combinations between january 2000 and march 2011] FROM DUAL AS years_months
Does anyone have any ideas how to do this? Can you use SELECT with some formula to βcreateβ data on the fly ?!
UPDATE:
Found it myself: generate days from a date range
The accepted answer in this question is what I am looking for. This may not be the easiest way, but it does what I want: fill in the selection with data based on the formula ....
To "create" a table "on the fly" with all the months of the last 10 years:
SELECT CONCAT(MONTHNAME(datetime), ' ' , YEAR(datetime)) AS YearMonth, MONTH(datetime) AS Month, YEAR(datetime) AS Year FROM ( select (curdate() - INTERVAL (aa + (10 * ba) + (100 * ca)) MONTH) as datetime from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c LIMIT 120 ) AS t ORDER BY datetime ASC
I have to admit that this is VERY exotic, but it works ...
I can use this select to connect it to my "orders" table and get the totals for each month, even if there is no data for a specific month.
But using a "numbers" or "calendar" table is probably the best option, so I'm going to use this.
date mysql select
Dylan
source share