Create a Cumulative Sum Column in MySQL

前端 未结 9 2124
青春惊慌失措
青春惊慌失措 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:30

    You could also create a trigger that will calculate the sum before each insert

    delimiter |
    
    CREATE TRIGGER calCumluativeSum  BEFORE INSERT ON someTable
      FOR EACH ROW BEGIN
    
      SET cumulative_sum = (
         SELECT SUM(x.count)
            FROM someTable x
            WHERE x.id <= NEW.id
        )
    
        set  NEW.cumulative_sum = cumulative_sum;
      END;
    |
    

    I have not tested this

提交回复
热议问题