我需要显示每年和每个月的“订单”总数。但是有几个月没有数据,但我确实想显示那个月(总价值为零)。我可以做一个“月”,每年有12个记录,但有没有办法获得一个月的范围,而不引入一个新的表格?
类似于:
SELECT [all year-month combinations between january 2000 and march 2011]
FROM DUAL AS years_months有人知道怎么做吗?您可以使用SELECT与某种公式,以“创建”数据的动态?!
更新:
我自己发现的:从日期范围生成天数
这个问题的公认答案是我想要的。也许不是最简单的方法,但它做了我想做的事情:根据公式填充一个select数据.
要“创建”过去10年中所有月份的动态表:
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 我必须承认,这是很有异国情调的,但它确实有效.
我可以使用这个选择加入我的“订单”表,并得到每个月的总数,即使在某个月没有数据的情况下。
但是使用“数字”或“日历”表可能是最好的选择,所以我将使用它。
发布于 2011-03-26 20:20:10
如果可能的话,尽量避免动态生成数据。它使非常简单的查询变得非常复杂,但最重要的是:它把优化器弄糊涂了。
如果需要一系列整数,请使用静态整数表。如果您需要一系列的日期、月份或其他什么,请使用日历表。除非您正在处理一些非常特殊的需求,否则静态表是可行的。
我给出了一个示例,说明如何在这个答案中创建一个数字表和一个最小的日历表(仅为日期)。
如果这些表已就位,则很容易解决查询。
发布于 2011-03-26 13:39:24
你可以试试这样的东西
select * from
(select 2000 as year union
select 2001 as year union
select 2009
) as years,
(select 1 as month union
select 2 as month union
select 3 as month union
select 4 as month union
select 5 as month union
select 6 as month union
select 7 as month union
select 8 as month union
select 9 as month
)
AS months
WHERE year between 2001 AND 2008 OR (year=2000 and month>0) OR (year = 2009 AND month < 4)
ORDER by year,month发布于 2011-03-26 13:37:28
在应用程序逻辑中完成查询之后,您可以填入剩下的几个月。
https://stackoverflow.com/questions/5442618
复制相似问题