简体   繁体   中英

Get percentage based on value in previous row

For the given data:

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

I want to calculate rum with percentage change of current and previous number.

rum = (currNumber - prevNumber) / prevNumber * 100

Expected result:

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

LAG function doesn't work here in MySQL.

Assuming the rows are ordered based on CID you can find previous row using correlated subquery:

SELECT CID, number, (
    SELECT (c.number - p.number) / p.number * 100
    FROM t AS p
    WHERE p.CID < c.CID
    ORDER BY p.CID DESC
    LIMIT 1
) AS rum
FROM t AS c

SQL Fiddle

You can emulate lag() with a variable:

set @num = null;

select 
    cid,
    number,
    (number- lag_number)/lag_number * 100 rum
from (
    select 
        cid, 
        @num lag_number, 
        @num := number number 
    from mytable 
    order by cid
) t
order by cid

Demo on DB Fiddle :

cid | number |  rum
--: | -----: | ---:
  1 | 1.0000 | null
  3 | 2.0000 |  100
  5 | 2.0000 |    0
  6 | 4.0000 |  100

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