MySQL:选择并补充特定列中的先前值

时间:2016-11-29 12:35:26

标签: mysql sql

有没有办法从表中选择值并汇总所有以前的值?

表样本:

+-------------+
| id | Amount |
+-------------+
|  1 |   10   |
|  2 |   10   |
|  3 |   10   |
|  4 |   10   |
|  5 |   10   |
|  6 |   10   |
|  7 |   10   |
+----+--------+

有没有办法从表中选择数据并加上“金额”值(总和以前的总和):

+-------------+
| id | Amount |
+-------------+
|  1 |   10   |
|  2 |   20   |
|  3 |   30   |
|  4 |   40   |
|  5 |   50   |
|  6 |   60   |
|  7 |   70   |
+----+--------+

THX,

1 个答案:

答案 0 :(得分:1)

在MySQL中,最有效的方法是使用变量:

select id, amount, (@sum := @sum + amount) as running_amount
from t cross join
     (select @sum := 0) params
order by id;