简体   繁体   English

Mysql中连续行之间的区别

[英]Difference between consecutive rows in Mysql

I would like to get the difference between 2 consecutive rows in the MySql. 我想得到MySql中2个连续行之间的差异。 I am trying to resolve, but no luck. 我正在努力解决,但没有运气。 Here is the data in the image 这是图像中的数据

http://i.stack.imgur.com/keIdU.png

I need a difference between rows of "Data2" column and results into "Diff" column. 我需要“ Data2”列的行与“ Diff”列的结果之间存在差异。

Thanks for your kind attention and much appreciated for your help. 感谢您的关注,也非常感谢您的帮助。

-Ram -内存

If the table have an auto incremental column 'id', We can order by id and identify the next row value and subtract it 如果表中有一个自动递增的列“ id”,我们可以按id排序并标识下一行的值并将其减去

SELECT t1.*, t1.Data2-(SELECT t2.Data2 FROM  `table_name`  t2 WHERE t2.id > t1.id LIMIT 1 ) AS difference
FROM `table_name`  t1
ORDER BY t1.id

to subtract from next row value 从下一行中减去

SELECT t1.*, t1.Data2-(SELECT t2.Data2 FROM  `table_name`  t2 WHERE t2.id < t1.id ORDER BY id DESC  LIMIT 1 ) AS difference
FROM `table_name`  t1
ORDER BY t1.id

Since you don't have a unique column in your table, you can achieve this by including a bind variable [ @rn & @rn1 ] which adds a unique number sequentially to every row in the table. 由于表中没有唯一的列,因此可以通过包含绑定变量[ @rn1 @rn@rn1 @rn ]来实现此目的,该变量将唯一的数字顺序地添加到表中的每一行。

Try this: 尝试这个:

SELECT tab1.application_id, tab1.fiscal_year, tab1.data1, coalesce(cast(tab1.data2 as signed) - 
                cast(tab2.data2 as signed), tab1.data2) as diff
  FROM 
      (SELECT b.application_id, @rn1:=@rn1+1 AS rank, b.fiscal_year, b.data1, b.data2
         FROM your_table b, (SELECT @rn1:=0) t1) as tab1,
      (SELECT a.application_id, @rn:=@rn+1 AS rank, a.fiscal_year, a.data1, a.data2
         FROM your_table a, (SELECT @rn:=0) t2) as tab2
 WHERE tab1.rank = tab2.rank + 1;

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

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