MYSQL组按天数间隔每天

时间:2016-09-14 21:37:45

标签: mysql date group-by intervals

我有一个查询,我在一个范围内每天运行多次。我想将此缩减为单个查询:

SELECT SUM(amount) AS all_time_revenue
FROM charges WHERE DATE(`charges`.`created_at`) <= '2015-03-01'

我在尝试将其转换为单个查询时遇到问题 - 我无法GROUP BY&#34; created_at&#34;因为我在和日期之前收取所有费用。 (不仅仅是在那个日期)。不确定这是否可行,但我确定是否有天才可以解决它。注意:如果我可以为每一行返回 myDate 以及 sum ,也会很好。

以下是我正在做的事情的完整示例:

$start_time = new DateTime('2016-08-01');
$end_time = new DateTime('2016-08-14');
$data = [];
for ($start_time; $start_time < $end_time; $start_time = $start_time->modify('+1 day')) {
     $date = $start_time->format("Y-m-d");

     $results = DB::SELECT("SELECT SUM(amount) AS all_time_revenue
                            FROM charges 
                            WHERE `charges`.`created_at` <= ? AND `charges`.`sandbox`=0",
                            ", [$date]);
     $data[$date] = $results[0]->all_time_revenue;
}

理想情况下,我想运行一个可以处理日期范围或单个日期和天数间隔的查询并将其吐出 行如:

row 1: ['2016-08-01', 4000.00]
row 2: ['2016-08-02', 4500.00]
...
row 14:['2016-08-14', 15000.00]

1 个答案:

答案 0 :(得分:0)

我认为以下查询代表您要查找的内容。它可以根据您的需要在日期范围下工作。它是一个生成累积总和的单个查询(从日期范围中给出的起始日期开始计算)。如果你想从epoch开始进行求和,那也可以完成。

create table tt (dt date, i integer);

insert into tt values("2016-01-01",1);

insert into tt values("2016-01-02",1);
insert into tt values("2016-01-02",2);

insert into tt values("2016-01-03",1);
insert into tt values("2016-01-03",2);
insert into tt values("2016-01-03",3);

insert into tt values("2016-01-04",1);
insert into tt values("2016-01-04",2);
insert into tt values("2016-01-04",3);
insert into tt values("2016-01-04",4);

insert into tt values("2016-01-05",1);
insert into tt values("2016-01-05",2);
insert into tt values("2016-01-05",3);
insert into tt values("2016-01-05",4);
insert into tt values("2016-01-05",5);

insert into tt values("2016-01-06",1);
insert into tt values("2016-01-06",2);
insert into tt values("2016-01-06",3);
insert into tt values("2016-01-06",4);
insert into tt values("2016-01-06",5);
insert into tt values("2016-01-06",6);
set @csum := 0;
select date_format(dt,'%Y-%m-%d') dt,@csum:=@csum+i as csum
from (
   select dt,sum(i) as i
   from tt 
   where dt between date('2016-01-02') and date('2016-01-05')
   group by dt
) as t1
order by 1;
|         dt | csum |
|------------|------|
| 2016-01-02 |    3 |
| 2016-01-03 |    9 |
| 2016-01-04 |   19 |
| 2016-01-05 |   34 |

如果你想从纪元开始获得累积总和,......

set @csum := 0;
select date_format(dt,'%Y-%m-%d') dt,@csum:=@csum+i as csum
from (
   select dt,sum(i) as i
   from tt 
   where dt<=date('2016-01-05')
   group by dt
) as t1
where dt<=date('2016-01-05') and date('2016-01-05')
order by 1;
|         dt | csum |
|------------|------|
| 2016-01-01 |    1 |
| 2016-01-02 |    4 |
| 2016-01-03 |   10 |
| 2016-01-04 |   20 |
| 2016-01-05 |   35 |