1

This question is based on my previous question given below. Get percentage based on value in previous row

Instead of getting a select statement, I want an update statement to fill the rum column using update query.

Input:

+---+--------+------+
|CID| number | rum  |
+---+--------+------+
| 1 | 1.0000 | NULL |
| 3 | 2.0000 | NULL |
| 5 | 2.0000 | NULL |
| 6 | 4.0000 | NULL |
+---+--------+------+

Output:

+---+--------+------+
|CID| number | rum  |
+---+--------+------+
| 1 | 1.0000 | NULL |
| 3 | 2.0000 |100.0 |
| 5 | 2.0000 |  0.0 |
| 6 | 4.0000 |100.0 |
+---+--------+------+

Formula:

rum = (currNumber - prevNumber) / prevNumber * 100
Tomrock D'souza
  • 121
  • 4
  • 13

1 Answers1

0

You can use a JOIN and window functions in an UPDATE. One method is:

update t join
       (select t.*, lag(number) over (order by cid) as prev_number
        from t
       ) tt
       on tt.cid = t.cid
    set rum = (number - prev_number) * 100 / prev_number;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786