Abstract: The
following describes a method implemented using two adjacent sql script data subtraction as follows:
Experiment Environment: sql server 2008 R2
Realization of ideas:
1. Use cte expression, the current table renumbered
2. Use the left join the table expression produces temporary dislocation were connected, and the new record generated two subtraction
create table [maomao365] (sort varchar(30),qty int);
go
----生成基础数据
insert into [maomao365](sort, qty)values
('maomaoA',10),('maomaoB',20),
('maomaoC',30),('maomaoD',40),
('maomaoE',50),('maomaoF',60)
go
with cte_temp as
(
select row_number() over(order by qty asc ) as keyId ,* from
[maomao365]
)
select a.sort,a.qty,b.qty,(isnull(a.qty,0)-isnull(b.qty,0)) as [相邻行之差] from cte_temp a
left join cte_temp b on a.keyId =(b.keyId+1) ---计算相邻两行之差
go
truncate table [maomao365]
drop table [maomao365]