加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

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

发布时间:2020-12-12 16:42:55 所属栏目:MsSql教程 来源:网络整理
导读:我已经收到了一些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)INSER
我已经收到了一些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

谢谢你的帮助.

解决方法

这可能会帮助你(有点).

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读