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.

0

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

it got right only for the first two rows. other value is wrong.
Edited my post now; earlier It was updating for iterative absolute_value. nevertheless, updated query would help.
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.

4 Comments

Can u please explain more? how do i use this
@Chit, when you create a trigger, its something like an automated action which will always happen BEFORE or AFTER an event. In your case you need it to happen BEFORE the UPDATE event. So using the trigger above will always subtract the new absvalue from the cum before updating the abs.
Mind you, triggers are not the SQL, so after specifying the trigger you then run your sql's
@Soe, here the best way to say thank you is to mark your question as solved by checking the answer which helped you most

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.