27,580
社区成员
发帖
与我相关
我的任务
分享
SELECT t.id, t.qty - t2.qty AS qtyDelta
FROM TTTT AS t
LEFT OUTER JOIN TTTT AS t2 ON t.id = ( SELECT MIN(id)
FROM TTTT
WHERE id > t2.id
)
if object_id('tb') is not null drop table tb
create table tb(id int, qty int)
insert tb
select 1,100 union all
select 2,80 union all
select 3,90 union all
select 4,120 union all
select 7,100
with t1 as
(
select *, row_number() over(order by id) as sn from tb t
)
select a.id, a.qty, a.qty-b.qty gap from t1 a left join t1 b on a.sn=b.sn+1
with a as(
select row_Number() over(order by id) rn,* from #a)
select x1.id,x1.qty,x1.qty-x2.qty
from a x1 left join a x2
on x1.rn=x2.rn+1
if object_id('tempdb.dbo.#A') is not null drop table #A
go
create table #A (ID int,QTY int)
insert into #A
select 1,100 union all
select 7,80 union all
select 3,90 union all
select 8,120 union all
select 5,100
select
list.ID,list.QTY,case when list.LastID is null then null else list.QTY - #A.QTY end as 差异
from (
select a.*,(select max(b.ID) from #A b where b.ID < a.ID) as LastID
from #A a
)list
left join #A
on #A.ID = list.LastID
order by list.ID
/*
ID QTY 差异
----------- ----------- -----------
1 100 NULL
3 90 -10
5 100 10
7 80 -20
8 120 40
*/
select
ID,QTY,(select b1.QTY-b2.QTY from TB as b2 where b2.ID<b1.ID order by ID desc limit 1) ChaYi
from TB as b1 order by ID