根据上一行的值获取百分比

时间:2019-11-13 08:53:10

标签: mysql sql window-functions

对于给定的数据:

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

我想用当前和上一个数字的百分比变化来计算朗姆酒。

rum = (currNumber - prevNumber) / prevNumber * 100

预期结果:

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

LAG函数在MySQL中不起作用。

2 个答案:

答案 0 :(得分:3)

假设根据CID对行进行排序,则可以使用相关子查询找到上一行:

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

答案 1 :(得分:1)

您可以使用变量模拟lag()

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