Mysql中连续行之间的差异

时间:2016-03-04 03:53:14

标签: mysql

我想了解MySql中连续2行之间的区别。我想解决,但没有运气。这是图像中的数据

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

我需要区分" Data2"列和结果进入" Diff"列。

感谢您的关注,非常感谢您的帮助。

-RAM

2 个答案:

答案 0 :(得分:0)

如果表格中有自动增量列' 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

从下一行值中减去

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

答案 1 :(得分:0)

由于您的表格中没有唯一的列,因此您可以通过包含绑定变量[@rn&amp; @rn1],为表中的每一行添加唯一编号

试试这个:

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;