日期:2014-05-18  浏览次数:20700 次

请问高手!!!
现在一张表:
ID VALUE
1 1000
2 1200
3 1600
4 1000
5 2000

想得到这样一张表:

ID VALUE
2 200
3 400
4 -600
5 2000

就是得到连续的ID的差值, 这样的SQL如何写?谢谢!!!


------解决方案--------------------
create table pk(id int identity(1,1),value int)
insert into pk select 1000
insert into pk select 1200
insert into pk select 1600
insert into pk select 1000
insert into pk select 2000

select id,[value]=(select a.value-value from pk where id+1=a.id) from pk a where a.id<>1
------解决方案--------------------
create table tb(ID int,VALUE int)
insert into tb values(1, 1000 )
insert into tb values(2, 1200 )
insert into tb values(3, 1600) 
insert into tb values(4, 1000 )
insert into tb values(5, 2000 )
go

select b.id , b.value - a.value value from tb a , tb b where a.id = b.id - 1
drop table tb

/*
id value
----------- ----------- 
2 200
3 400
4 -600
5 1000

(所影响的行数为 4 行)
*/