简体   繁体   English

mysql中两个连续行之间的差异

[英]difference between two consecutive rows in mysql

I have a table in MySQL database: 我在MySQL数据库中有一个表:

  id     ts            number
1   07-10-2017 00:00    200
2   07-10-2017 00:01    300
3   07-10-2017 00:02    700
4   07-10-2017 00:03    1000

I want to calculate difference between two consecutive rows and i need output format be like: 我想计算两个连续行之间的差异,我需要输出格式如下:

id        ts           number   o/p
1   07-10-2017 00:00    200      0
2   07-10-2017 00:01    300     100
3   07-10-2017 00:02    700     400
4   07-10-2017 00:03    1000    300

I want first value of o/p column to be 0 and rest is the difference. 我希望o / p列的第一个值为0,其余是差异。

Any help would be appreciated. 任何帮助,将不胜感激。

Use a self-join: 使用自联接:

SELECT
    t1.ts,
    t1.number,
    t1.number - COALESCE(t2.number, t1.number) AS diff
FROM yourTable t1
LEFT JOIN yourTable t2
    ON t1.id = t2.id + 1
ORDER BY
    t1.ts;

在此输入图像描述

Demo 演示

You can do this with a local variable: 您可以使用局部变量执行此操作:

SET @tmp := -1;
SELECT id,
 ts ,
 number,
 if(@tmp =-1, 0, number - @tmp) as 'o/p',
 @tmp:=number as dummy
FROM YourTable
Order by ts;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM