如果我想将当前行减去上一行,我应该查询什么?我将在 vb6 中循环使用它。 像这样的东西:
Row
1
2
3
4
5
在第一个循环中,值 1 不会被扣除,因为它没有前一行,这是可以的。 下一个循环的值 2 将减去上一行的值 1。依此类推,直到最后一行。
我怎样才能实现这个例程? 通过 SQL 查询或 VB6 代码。任何都可以。
最佳答案
假设您有一个排序列(例如 id
),那么您可以在 SQL Server 2012 中执行以下操作:
select col,
col - coalesce(lag(col) over (order by id), 0) as diff
from t;
在 SQL Server 的早期版本中,您可以使用相关子查询执行几乎相同的操作:
select col,
col - isnull((select top 1 col
from t t2
where t2.id < t.id
order by id desc
), 0)
from t
这里使用 isnull()
而不是 coalesce()
,因为 SQL Server 中存在一个“错误”,在使用 coalesce() 时会对第一个参数求值两次
.
您还可以使用 row_number()
执行此操作:
with cte as (
select col, row_number() over (order by id) as seqnum
from t
)
select t.col, t.col - coalesce(tprev.col, 0) as diff
from cte t left outer join
cte tprev
on t.seqnum = tprev.seqnum + 1;
所有这些都假设您有一些用于指定排序的列。它可能是一个id
,或者一个创建日期或其他东西。 SQL 表本质上是无序的,因此不存在没有指定顺序的列的“前一行”。
关于sql-server - 如何减去sql中的前一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17560829/