简体   繁体   中英

Sum up values from rows in MySQL table

I have added a new column 'sums' to my table and I am trying to sum up values from 'vals' column then update 'sums' in the same table, according to the algorithm shown below in the table.

I could write a few loops in PHP but I don't think it would be nice.

Any clue how to write it nicely?

--------------------------------------------------
|  id   |  sets   |  parts  |  vals    |  sums   |
|-------|---------|---------|----------|---------|
|   1   |    1    |    1    |    2     |    2    |
|-------|---------|---------|----------|---------|
|   2   |    1    |    2    |    3     |  2+3=5  |
|-------|---------|---------|----------|---------|
|   3   |    1    |    3    |    5     |2+3+5=10 |
|-------|---------|---------|----------|---------|
|   4   |    2    |    1    |    4     |    4    |
|-------|---------|---------|----------|---------|
|   5   |    2    |    2    |    1     |  4+1=5  |
|-------|---------|---------|----------|---------|
|   6   |    2    |    3    |    2     | 4+1+2=7 |
|-------|---------|---------|----------|---------|
|   7   |    3    |    1    |    6     |    6    |
|-------|---------|---------|----------|---------|

This should return the value you want for sums:

SELECT t.id
     , IF(t.sets=@prev_sets,@i:=@i+t.vals,@i:=t.vals) AS `sums`
     , @prev_sets := t.sets AS prev_sets
  FROM mytable t
  JOIN (SELECT @prev_sets := NULL, @i := 0 ) i
 ORDER BY t.sets, t.parts

You can use this as an inline view in an update statement

UPDATE ( SELECT t.id
              , IF(t.sets=@prev_sets,@i:=@i+t.vals,@i:=t.vals) AS `sums`
              , @prev_sets := t.sets AS prev_sets
           FROM mytable t
           JOIN (SELECT @prev_sets := NULL, @i := 0 ) i
          ORDER BY t.sets, t.parts
       ) s
  JOIN mytable r
    ON r.id = s.id
   SET r.sums = s.sums

From the example data, it looks like you want the "groupings" on sets , and you want to order on parts within each group.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM