mssql sqlserver 使用sql脚本实现相邻两条数据相减的方法分享


摘要:
下文讲述使用sql脚本实现相邻两条数据相减的方法,如下所示:
实验环境:sql server 2008 R2



实现思路:
1.使用cte表达式,对当前表进行重新编号
2.使用左连接对 表达式 生成的临时表进行错位连接,并对生成的新纪录中两列进行相减

    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]
   
mssql_sqlserver_相邻行之差计算_8718

mssql_sqlserver_相邻行之差计算_8718