4

I have table with two columns namely cumulative_sum and absolute. But I only have cumulative value. I would like to calculate absolute value.

Cumulative Value
12
19
32
41

Expected Absolute Value
12
7
13
9

I have try a query like this. I just need to update @absvalue to cum every time query update.

set @absvalue := 0;
update pdb_tint_result set abs = (cum - @absvalue)
where user_id='P6'
order by date;

Can you please guide me?

I saw calculating cumulative sum here I try to make it work for calculation Abs value.

Community
  • 1
  • 1
Soe Chit Kaung
  • 268
  • 1
  • 3
  • 11

2 Answers2

2

Try this one -

SET @prev_cum:=0;
UPDATE test_point_sum 
   SET absolute_value = (cumulative_sum - @prev_cum),
       cumulative_sum = @prev_cum:=cumulative_sum 
   ORDER BY 
      ID ASC;

Pick your table and column names. tested and verified. see if this helps

DRapp
  • 47,638
  • 12
  • 72
  • 142
stack_d_code
  • 1,196
  • 2
  • 12
  • 19
1

If you want to do something automatically with a changing variable I will recommend using triggers. To use triggers in your case

"CREATE TRIGGER update_abs 
 BEFORE UPDATE ON pdb_tint_result
 FOR EACH ROW SET abs = cum - New.absvalue;"

I hope it helped.

Gideon Appoh
  • 678
  • 1
  • 6
  • 15