我需要显示每年和每月的"订单"总数.但有几个月没有数据,但我想显示那个月(总值为零).我可以用每年12条记录创造一个可靠的'月',但是有没有办法在不引入新表的情况下获得一系列月份?
就像是:
SELECT [all year-month combinations between january 2000 and march 2011]
FROM DUAL AS years_months
Run Code Online (Sandbox Code Playgroud)
有人知道怎么做吗?你可以使用SELECT和某种公式来"动态创建"数据吗?!
更新:
自己发现: 从日期范围生成天数
这个问题中接受的答案是我正在寻找的.也许不是最简单的方法,但它可以做我想要的:根据公式填充数据选择....
在过去十年的所有月份中"创建"一张桌子:
SELECT CONCAT(MONTHNAME(datetime), ' ' , YEAR(datetime)) AS YearMonth,
MONTH(datetime) AS Month,
YEAR(datetime) AS Year
FROM (
select (curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) 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
Run Code Online (Sandbox Code Playgroud)
我必须承认,这是非常奇特的,但它的工作......
我可以使用此选项将其与我的'orders'表连接,并获得每月的总数,即使某个月没有数据也是如此.
但使用'数字'或'日历'表可能是最好的选择,所以我将使用它.
你可以尝试这样的事情
选择*从
(选择2000作为年度工会
选择2001年作为年度工会
选择2009
),
(选择1作为月份联合
选择2作为月份联合
选择3作为月份联合
选择4作为月份联合
选择5作为月份联合
选择6作为月份联合
选择7作为月份联合
选择8作为月份联合
选择9作为月份
)
AS months
WHERE year between 2001 AND 2008 OR (year=2000 and month>0) OR (year = 2009 AND month < 4)
ORDER by year,month
Run Code Online (Sandbox Code Playgroud)