MySQL SELECT function to sum current data

后端 未结 3 339
醉酒成梦
醉酒成梦 2020-12-21 12:11

I have a query that return something like this:

| ID | Val |  
| 0  | 10  |     
| 1  | 20  |     
| 2  | 30  |  

But instead of that, I wa

相关标签:
3条回答
  • 2020-12-21 12:52

    Assuming the table name is t, you can use a query like this:

    select t.id, t.val, sum(t2.val) Sum
      from t, t t2
     where t2.id <= t.id
    group by t.id, t.val
    

    (tested in Oracle)

    0 讨论(0)
  • 2020-12-21 12:54

    Would something like this work for your purposes? (Warning, potentially really darned slow with the subselect).

    SELECT t1.id, t1.val, (SELECT SUM(val) FROM table AS t2 WHERE t2.id <= t1.id) 'sum'
       FROM table AS t1
       ORDER BY id ASC
    
    0 讨论(0)
  • 2020-12-21 12:56

    This is called cumulative sum.

    In Oracle and PostgreSQL, it is calculated using a window function:

    SELECT  id, val, SUM() OVER (ORDER BY id ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
    FROM    mytable
    

    However, MySQL does not support it.

    In MySQL, you can calculate it using session variables:

    SET @s = 0;
    
    SELECT  id, val, @s := @s + val
    FROM    mytable
    ORDER BY
            id
    ;
    

    or in a pure set-based but less efficient way:

    SELECT  t1.id, t1.val, SUM(t2.val)
    FROM    mytable t1
    JOIN    mytable t2
    ON      t2.id <= t1.id
    GROUP BY
            t1.id
    ;
    
    0 讨论(0)
提交回复
热议问题