How do I lag columns in MySQL?

前端 未结 2 1547
野趣味
野趣味 2020-11-28 14:01

Consider the following table:

SELECT id, value FROM table ORDER BY id ASC;
+-----+---------+
| id  | value   |
+-----+---------+
| 12  | 158     |
| 15  | 34         


        
2条回答
  •  情深已故
    2020-11-28 14:21

    Here is a solution that returns what you want in MySQL

    SET @a :=0;
    SET @b :=2;
    SELECT r.id, r.value, r.value/r2.value AS 'lag'
    FROM
    (SELECT if(@a, @a:=@a+1, @a:=1) as rownum, id, value FROM results) AS r
    LEFT JOIN
    (SELECT if(@b, @b:=@b+1, @b:=1) as rownum, id, value FROM results) AS r2
    ON r.rownum = r2.rownum
    

    MySQL 5.1 doesn't like a self join against a subquery so you have to count rows twice, so not as tidy or scalable as it might be, but it does make specifying the lag simple.

    For readers that use Oracle instead this is much easier

    SELECT id, value, value/lag(value, 2) over (order by id) as lag from results;
    

提交回复
热议问题