MySQL减去同一列中的连续行

时间:2014-06-03 18:53:59

标签: mysql

我的问题与此SO post类似,但区别在于我没有顺序ID列。

我有一个表格如下

ID | length
0  |  5
0  |  7
0  |  10
1  |  3
1  |  8
1  |  12
2  |  1
2  |  2
2  |  4
2  |  5

我希望得到按ID分组的长度列中连续行之间的差异。所以应该给出

ID | length | difference
0  |  5     | NULL
0  |  7     | 2
0  |  10    | 3
1  |  3     | NULL
1  |  8     | 5
1  |  12    | 4
2  |  1     | NULL
2  |  2     | 1
2  |  4     | 2
2  |  5     | 1

我不知道该怎么做。我尝试给每个ID一个单独的ID,这是顺序的,但事实证明是复杂的,我无法让它工作。有人可以建议一个更好的方法吗?

2 个答案:

答案 0 :(得分:2)

假设(id,length)是UNIQUE ......

SELECT x.*
     , x.length - MAX(y.length) diff  
  FROM my_table x 
  LEFT 
  JOIN my_table y 
    ON y.id = x.id 
   AND y.length < x.length 
 GROUP 
    BY x.id
     , x.length;

答案 1 :(得分:1)

select a.id, a.length, b.length, b.length - a.length as difference
from mytable a, mytable b
where a.id=b.id
and b.length = (select min(length) from mytable where id=a.id and length > a.length)
相关问题