我有这个表名“ History”:
------------------------------------------------
| id | account_id | amount | type | date
------------------------------------------------
| 1 | 3 | 100 | topup| 2018-01-01
------------------------------------------------
| 2 | 2 | 50 | topup| 2018-01-02
------------------------------------------------
| 3 | 3 | -2 | usage| 2018-01-03
------------------------------------------------
| 4 | 3 | -1 | usage| 2018-01-04
------------------------------------------------
| 5 | 2 | -1 | usage| 2018-01-05
------------------------------------------------
| 6 | 3 | -2 | usage| 2018-01-06
------------------------------------------------
我想创建查询以按account_id计算每一行,以计算每个帐户的当前余额,如下所示:
---------------------------------------------------------
| id | account_id | amount | type | date | balance
---------------------------------------------------------
| 1 | 3 | 100 | topup| 2018-01-01| 100
---------------------------------------------------------
| 2 | 2 | 50 | topup| 2018-01-02| 50
---------------------------------------------------------
| 3 | 3 | -2 | usage| 2018-01-03| 98
---------------------------------------------------------
| 4 | 3 | -1 | usage| 2018-01-04| 97
---------------------------------------------------------
| 5 | 2 | -1 | usage| 2018-01-05| 49
---------------------------------------------------------
| 6 | 3 | -2 | usage| 2018-01-06| 94
---------------------------------------------------------
我尝试过这个:
SELECT *
FROM (
SELECT id, SUM(amount) OVER (ORDER BY id, account_id) AS balance
FROM history
GROUP BY account_id
) as foo
ORDER BY date;
但是我得到的字段余额没有正确的结果,有任何线索吗?
答案 0 :(得分:0)
SELECT
*,
SUM(amount) OVER (PARTITION BY account_id ORDER BY date)
FROM
history
ORDER BY id
accounts_id
创建分区date
SUM()
现在可以使用,但是当前顺序为(account_id, date)
id