我们在写SQL的时候,会有这种需求:对表中的数据累计求和。
| id | money |
|---|---|
| 1 | 10 |
| 2 | 20 |
| 3 | 30 |
求出结果
| id | money | sumMoney |
|---|---|---|
| 1 | 10 | 10 |
| 2 | 20 | 30 |
| 3 | 30 | 60 |
累加sql:
方法一:
SELECT a.id,a.money,SUM(lt.money) as cum
FROM cum_demo a JOIN cum_demo lt
ON a.id >= lt.id
GROUP BY a.money
ORDER BY id
方法二:
SET @csum := 0;
SELECT id, money, (@csum := @csum + money) AS sumMoney
FROM money;












网友评论