摘要:
下文講述使用sql腳本實現相鄰兩條數據相減的方法,以下所示:
實驗環境:sql server 2008 R2sql
實現思路:
1.使用cte表達式,對當前表進行從新編號
2.使用左鏈接對 表達式 生成的臨時表進行錯位鏈接,並對生成的新紀錄中兩列進行相減
spa
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]