27

mysql 在给定范围内生成一系列日期的最佳方法是什么?

我想到的应用程序是编写一个报告查询,它为每个日期返回一行,而不管是否有任何数据要报告。最简单的形式:

select dates.date, sum(sales.amount)
from <series of dates between X and Y> dates
left join sales on date(sales.created) = dates.date
group by 1

我尝试过创建一个包含很多日期的表格,但这似乎是一个糟糕的解决方法。

4

4 回答 4

34

如果您处于像我这样禁止创建临时表并且也不允许设置变量的情况,但是您想生成特定时期内的日期列表,例如当前年份进行一些汇总,请使用此

select * from 
(select adddate('1970-01-01',t4*10000 + t3*1000 + t2*100 + t1*10 + t0) gen_date from
 (select 0 t0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 t1 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 t2 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 t3 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 t4 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where gen_date between '2017-01-01' and '2017-12-31'
于 2017-09-01T01:41:07.613 回答
21

我认为有一个日历表是个好主意。您可以获得大量报告和查询功能,尤其是在填充稀疏数据范围时。

我发现这篇文章似乎是一个很好的例子。

于 2012-12-31T18:43:09.430 回答
8

您可以使用变量生成日期系列:

Set @i:=0;
SELECT DATE(DATE_ADD(X, 
INTERVAL @i:=@i+1 DAY) ) AS datesSeries
FROM yourtable, (SELECT @i:=0) r
where @i < DATEDIFF(now(), date Y) 
;

不确定这是否是您尝试过的:)。

接下来使用上面生成的查询作为表left join

set @i:=0;

select
d.dates,
sum(s.amount) as TotalAmount
from(
SELECT DATE(DATE_ADD(X, 
INTERVAL @i:=@i+1 DAY) ) AS dateSeries
FROM Sales, (SELECT @i:=0) r
where @i < DATEDIFF(now(), date Y) 
) dates d 
left join Sales s
on Date(s.Created) = Date(d.dateSeries)
group by 1
;
于 2012-12-31T18:40:44.720 回答
4

您还可以使用临时表来生成日期系列。检查以下查询:

CREATE TEMPORARY TABLE daterange (dte DATE); 

SET @counter := -1;
WHILE (@counter < DATEDIFF(DATE(_todate), DATE(_fromdate))) DO 
    INSERT daterange VALUES (DATE_ADD(_fromdate, INTERVAL @counter:=@counter + 1 DAY));
END WHILE;

SELECT dates.dte, SUM(sales.amount)
FROM daterange dates
LEFT JOIN sales ON DATE(sales.created) = dates.date
GROUP BY dates.dte;
于 2013-01-01T12:38:42.220 回答