现有表A:字段hh(行号),date(日期),ye1(当前值),ye2(比上日)
内容:1000,20130101,10,0表示行号1000,2013年1月1日的数据为10,比上日为0
内容:1000,20130102,15,ye2(此值应该是15-10=5)
内容:1000,20130103,18,ye2(此值应该是18-15=3)
现在就想把第二条记录的ye2的值根据第一条来更新的语句怎么写,以此类推!谢谢!
内容:1000,20130101,10,0表示行号1000,2013年1月1日的数据为10,比上日为0
内容:1000,20130102,15,ye2(此值应该是15-10=5)
内容:1000,20130103,18,ye2(此值应该是18-15=3)
现在就想把第二条记录的ye2的值根据第一条来更新的语句怎么写,以此类推!谢谢!
declare @t table ([date] smalldatetime,ye1 int,ye2 int)
insert into @t
select '20130101',10,0 union all
select '20130102',15,0 union all
select '20130103',18,0 update a set a.ye2=a.ye1-b.ye1 from @t a inner join @t b on a.[date]=b.[date]+1
select * from @t/*
查询结果
date ye1 ye2
------------------------------------------------------ ----------- -----------
2013-01-01 00:00:00 10 0
2013-01-02 00:00:00 15 5
2013-01-03 00:00:00 18 3*/
drop table #t1
create table #t1
(
id int identity(1,1),
a varchar(20),
b varchar(20),
c int,
d int
)
insert into #t1(a,b,c,d)
select '1000','20130101',10,0insert into #t1(a,b,c,d)
select '1000','20130102',15,15-c
from #t1 where id=
(
select max(id) from #t1
)
insert into #t1(a,b,c,d)
select '1000','20130103',18,18-c
from #t1 where id=
(
select max(id) from #t1
)
select * from #t1
当然,你可以查询一下更新结果
select * from A
update A set A.ye2=A.ye1-B.ye1 from A inner join A as B on A.hh=B.hh