mysql 日期滞后,在MySQL上模拟滞后函数

I'm trying to get lagged values (current row - last row) from the following table:

+-------+------------+-------------+---------------------+

| index | codigowine | preconormal | timestamp |

+-------+------------+-------------+---------------------+

| 2 | 10088 | 65.60 | 2014-11-18 23:39:08 |

| 1005 | 10088 | 62.60 | 2014-11-20 11:00:14 |

| 2028 | 10088 | 62.60 | 2014-11-21 09:00:13 |

| 3092 | 10088 | 62.60 | 2014-11-22 09:00:12 |

| 5083 | 10088 | 69.00 | 2014-11-24 09:00:13 |

+-------+------------+-------------+---------------------+

The expected output should be:

+-------+------------+-------------+---------------------+-----------+

| index | codigowine | preconormal | timestamp | lag_price |

+-------+------------+-------------+---------------------+-----------+

| 2 | 10088 | 65.60 | 2014-11-18 23:39:08 | 0.00 |

| 1005 | 10088 | 62.60 | 2014-11-20 11:00:14 | -3.00 |

| 2028 | 10088 | 62.60 | 2014-11-21 09:00:13 | 0.00 |

| 3092 | 10088 | 62.60 | 2014-11-22 09:00:12 | 0.00 |

| 5083 | 10088 | 69.00 | 2014-11-24 09:00:13 | 6.40 |

+-------+------------+-------------+---------------------+-----------+

I've seen some examples emulating the lag function on MySQL by setting a variable and calculating the difference between rows, but I just can't get it to work:

SET @price=0;

select index,codigowine,@price price_lag, @price:=preconormal curr_price from precos order by codigowine, timestamp;

Other possibilities would be to calculate using php or adding a new table and doing the programming via python, but I'm trying to avoid these possibilities if I'm able to perform this through SQL.

解决方案

Ok, so after some more digging, and the suggestion by @Marc B, I finally got to where I wanted. In case anyone else needs help, here's my answer:

set @price = (select preconormal from precos where codigowine='10088' order by timestamp asc limit 1);

On the line above I'm setting @price to the first record instead of zero, to avoid getting a lag_price of 65.60 on the first row.

Below is the actual result:

select codigowine, preconormal - @price as lag_price, @price:=preconormal curr_price from precos WHERE codigowine='10088' order by timestamp;

Here's the fiddle working.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值