1:搂主的表应该有一个排序的方法,假设有一个表
Table1
(
value int,
insertdate datetime
)
15,17,19,22分别是不同纪录的value值,insertdate表示值得先后顺序
则
1:创建一个临时表,重新对值进行排序,并新增加一个栏位自增长ID,方法为:
select identity(int,1,1) as id,value,insertdate
into #temptable from table1 order by insertdate
2:对临时表#temptable进行查询计算,方法为:
select convert(varchar,b.value)+'-'+Convert(varchar,a.value) as statement,
b.value-a.value as resultdate
from #temptable as b
left join #temptable as a on b.id= a.id+1
如果表中數據是按這種格式排列的話,也可以不用加自增列
--建立測試環境
Create Table A
(a Int)
--插入數據
Insert A Select 15
Union All Select 17
Union All Select 19
Union All Select 22
--測試
Select
T.a,
(T.a-(Select Top 1 a from A Where a<T.a Order By a Desc)) As 列差
from A T
--刪除測試環境
Drop Table A
--結果
/*
a 列差
15 NULL
17 2
19 2
22 3
*/