我有一张表格如下
+---+------------+----------+
| ID| Date | Amount_1 |
+---+------------+----------+
| 1 | 2016-02-02 | 100.00 |
| 1 | 2016-02-05 | 150.00 |
| 1 | 2016-02-09 | 125.00 |
| 1 | 2016-02-11 | 75.00 |
| 1 | 2016-02-19 | -46.99 |
| 1 | 2016-02-20 | -41.33 |
| 1 | 2016-02-29 | -14.15 |
+---+------------+----------+
我希望在此表格中推导出 Amount_1 中的 Amount_2 ,并且Amount_2的每一行的值必须是上一行和当前行的总和。 Amount_1 列。
我的意思是我想得到下表。
+---+------------+----------+----------+
| ID| Date | Amount_1 | Amount_2 |
+---+------------+----------+----------+
| 1 | 2016-02-02 | 100.00 | 100.00 |
| 1 | 2016-02-05 | 150.00 | 250.00 |
| 1 | 2016-02-09 | 125.00 | 375.00 |
| 1 | 2016-02-11 | 75.00 | 450.00 |
| 1 | 2016-02-19 | -46.99 | 403.01 |
| 1 | 2016-02-20 | -41.33 | 361.68 |
| 1 | 2016-02-29 | -14.15 | 347.53 |
+---+------------+----------+----------+
答案 0 :(得分:1)
试试这样:
SELECT m.ID, m.Date, m.Amount_1, (@x:= m.Amount_1 + @x) AS Amount_2
FROM mytable m,(SELECT @x:=0) c
答案 1 :(得分:1)
您可以使用session varable
SET @old_amount = 0;
SELECT ID, Date,Amount_1, (@old_amount := Amount_1 + @old_amount) AS Amount_2
FROM table_name
ORDER BY date;