Create a Cumulative Sum Column in MySQL

前端 未结 9 2131
青春惊慌失措
青春惊慌失措 2020-11-22 00:05

I have a table that looks like this:

id   count
1    100
2    50
3    10

I want to add a new column called cumulative_sum, so the table wou

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 00:23

    MySQL 8.0/MariaDB supports windowed SUM(col) OVER():

    SELECT *, SUM(cnt) OVER(ORDER BY id) AS cumulative_sum
    FROM tab;
    

    Output:

    ┌─────┬──────┬────────────────┐
    │ id  │ cnt  │ cumulative_sum │
    ├─────┼──────┼────────────────┤
    │  1  │ 100  │            100 │
    │  2  │  50  │            150 │
    │  3  │  10  │            160 │
    └─────┴──────┴────────────────┘
    

    db<>fiddle

提交回复
热议问题