MySQL query that computes partial sums

前端 未结 2 1037
礼貌的吻别
礼貌的吻别 2021-01-14 19:32

What query should I execute in MySQL database to get a result containing partial sums of source table?

For example when I have table:

Id|Val
1 | 1
2         


        
相关标签:
2条回答
  • 2021-01-14 20:01

    You can do this by joining the table on itself. The SUM will add up all rows up to this row:

    select cur.id, sum(prev.val)
    from TheTable cur
    left join TheTable prev
        on cur.id >= prev.id
    group by cur.id
    

    MySQL also allows the use of user variables to calculate this, which is more efficient but considered something of a hack:

    select 
         id
    ,    @running_total := @running_total + val AS RunningTotal
    from TheTable
    
    0 讨论(0)
  • 2021-01-14 20:01
    SELECT l.Id, SUM(r.Val) AS Val
    FROM your_table AS l
        INNER JOIN your_table AS r
            ON l.Val >= r.Val
    GROUP BY l.Id
    ORDER By l.Id
    
    0 讨论(0)
提交回复
热议问题