MySQL累积总和

时间:2016-12-14 20:19:30

标签: mysql select running-total

我有这样的表:

FType | Vehicle   | Driver | Time    | QTY  
----------------------------------------------  
 ED   |   1       |  A     |20:57:51 |  5
 ED   |   1       |  A     |20:59:10 |  7
 ED   |   2       |  B     |20:58:40 |  6
 ED   |   2       |  B     |21:30:10 |  4
 ED   |   3       |  C     |21:48:33 |  1

现在我需要总结每个司机的QTY,如果时间是< 10分钟, 如果没有那么只需打印数量

结果应该是:

FType | Vehicle   | Driver |  TotQTY
----------------------------------------------  
 ED   |   1       |  A     | 12
 ED   |   2       |  B     | 6
 ED   |   2       |  B     | 4
 ED   |   3       |  C     | 1

怎么做?

1 个答案:

答案 0 :(得分:0)

这是基于Barmar建议的用户定义变量的解决方案,但另外还考虑了驱动程序的分组。内部查询计算同一驱动程序的哪些时间属于同一组,而外部查询则计算每个组的数量和。希望它有所帮助。

drop table if exists test2;

create table test2 (
driver varchar(20), time time, qty int
);

insert into test2 values ('A', '20:57:51', 5);
insert into test2 values ('A', '20:59:10', 7);
insert into test2 values ('B', '20:58:40', 6);
insert into test2 values ('B', '21:30:10', 4);
insert into test2 values ('C', '21:48:33', 1);


set @driver='', @time:= '00:00:00', @group:=0; 
select driver, sum(qty) from (select @group := if (@driver = driver and TIMEDIFF(time, @time) < 600, @group, @group + 1) as samegroup, @driver := driver as driver, @time := time as time, qty from test2) groupedqty group by driver, samegroup