在SQL中从另一行中减去一行数据

Doc*_*ken 12 mysql sql join subtraction

我已经厌倦了一些SQL,我有几行数据,我想从前一行中减去一行并让它一直重复.

所以这是表:

CREATE TABLE foo (
  id,
  length
)
INSERT INTO foo (id,length) VALUES(1,1090)
INSERT INTO foo (id,length) VALUES(2,888)
INSERT INTO foo (id,length) VALUES(3,545)
INSERT INTO foo (id,length) VALUES(4,434)
INSERT INTO foo (id,length) VALUES(5,45)

我希望结果显示第三列称为差异,这一行是从下面的一行减去,最后一行从零减去.

+------+------------------------+
| id   |length |  difference  |
+------+------------------------+
|    1 | 1090  |  202         |
|    2 |  888  |  343         |
|    3 |  545  |  111         |
|    4 |  434  |  389         |
|    5 |   45  |   45         |

我尝试过自我加入,但我不确定如何限制结果,而不是让它自行循环.我不能依赖于给定结果集的id值是顺序的,所以我没有使用那个值.我可以扩展架构以包含某种顺序值.

这就是我尝试过的:

SELECT id, f.length, f2.length, (f.length - f2.length) AS difference
FROM foo f, foo f2

谢谢你的帮助.

sha*_*esh 13

这可能对你有所帮助(有点).


select a.id, a.length, 
coalesce(a.length - 
    (select b.length from foo b where b.id = a.id + 1), a.length) as diff
from foo a


The*_*iot 6

Yipee!这样做的诀窍:

SELECT  f.id, f.length, 
    (f.length - ISNULL(f2.length,0)) AS diff
FROM foo f
LEFT OUTER JOIN foo f2
ON  f2.id = (f.id +1)
Run Code Online (Sandbox Code Playgroud)

请检查其他情况,它适用于您发布的值!请注意,这适用于SQL Server 2005