MySql - 从开始数到每一天

MySql - count from beginning until each day

假设我有以下 table(请记住,这个 table 将有 10000 多行):

id    total           date
1       5        2015-05-16
2       8        2015-05-17
3       4        2015-05-18
4       9        2015-05-19
5       3        2015-05-20

我希望查询给出以下结果:

1
date => 2015-05-16
total => 5

2
date => 2015-05-17
total => 13

3
date => 2015-05-18
total => 17

4
date => 2015-05-19
total => 26

5
date => 2015-05-20
total -> 29

我现在想不出有任何查询可以执行此操作,这就是为什么我没有提供我尝试过的任何代码的原因。

有什么想法吗?我不确定这是否仅适用于 mysql,也许我必须使用 php.

你可以做到 -

SELECT 
     a.id, 
     a.date, 
    (SELECT SUM(b.total) FROM your_table WHERE b.date <= a.date) as new_total       
FROM your_table a, your_table b 
ORDER BY a.date ASC

这可以在 mysql 中使用用户定义的变量来完成,然后得到 运行 总计

select
id,
total,
date
date from
(
 select
 id,
 @tot:= @tot+total as total,
 date from my_table,(select @tot:=0)x
 order by date
)x

应该这样做:

select id, (select sum(total) from table a where a.date <= b.date)  from table b