生成一系列日期

Boh*_*ian 20 mysql

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
Run Code Online (Sandbox Code Playgroud)

我已经尝试创建一个包含大量日期的表,但这似乎是一个糟糕的解决方法.

Bel*_*Bob 19

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

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


com*_*eak 15

如果你在像我这样的情况下禁止创建临时表,并且也不允许设置变量,但是你想生成一个特定时期的日期列表,比如当前年份做一些聚合,使用这个

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'
Run Code Online (Sandbox Code Playgroud)


bon*_*igo 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) 
;
Run Code Online (Sandbox Code Playgroud)

不知道这是不是你尝试过:).

接下来使用上面生成的查询作为表来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
;
Run Code Online (Sandbox Code Playgroud)


Sah*_*hah 5

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

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;
Run Code Online (Sandbox Code Playgroud)

  • 由于这个问题仅被 MySQL 标记,这不是 MySQL 有效代码,这是 SQL Server (MSSQL) (3认同)