MySQL select “accumulated” column

前端 未结 4 1008
故里飘歌
故里飘歌 2020-12-16 23:30

I\'m not sure what to call this besides an \"accumulated\" column.

I have a MySQL table with a column that looks like

+---+
|val|
+---+
| 1 |
| 4 |
|         


        
4条回答
  •  被撕碎了的回忆
    2020-12-16 23:44

    Another variation (single line) can be

    SELECT val, @sm := @sm + val AS sum
      FROM myTable, (SELECT @sm := 0) r;
    

    If you don't want to use variables you can use nested select however note that this query has higher complexity (lower performance) and you must set and anchor for sorting, in my example I used _rowid but any other field can do the job

      SELECT x1.val, (SELECT sum(val)
                        FROM myTable
                       WHERE id <= x1._rowid)
                        AS sum
        FROM myTable AS x1
    ORDER BY _rowid;
    

提交回复
热议问题