对每一行求和,然后在每一行的新字段中显示结果

时间:2019-09-09 07:36:39

标签: sql postgresql

我有这个表名“ 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;

但是我得到的字段余额没有正确的结果,有任何线索吗?

1 个答案:

答案 0 :(得分:0)

demo:db<>fiddle

SELECT
    *,
    SUM(amount) OVER (PARTITION BY account_id ORDER BY date)
FROM
    history
ORDER BY id
  1. 为您的accounts_id创建分区
  2. 通过date
  3. 对其进行排序
  4. 累积SUM()现在可以使用,但是当前顺序为(account_id, date)
  5. 通过id
  6. 对它们重新排序