求个sql文,今天还有人吗
表A
有如下字段(a,b,c,d,Year,amount,amountbefore)
其中a,b,c,d,date是主键
数据举例如下
(aa,bb,cc,dd,2012,2000,null)
(aa,bb,cc,dd,2013,5000,null)
我想把第一条作为九数据的2000给取道新数据的amountbefore里,即
(aa,bb,cc,dd,2013,5000,2000)
只要帮我求出来2012数据的amount{2000}这个值就可以,多谢
[解决办法]
if object_id('[TB]') is not null drop table [TB]
go
create table [TB] (a nvarchar(4),b nvarchar(4),c nvarchar(4),d nvarchar(4),Year int,amount int,amountbefore sql_variant)
insert into [TB]
select 'aa','bb','cc','dd',2012,2000,null union all
select 'aa','bb','cc','dd',2013,5000,null
select * from [TB]
SELECT A.a,A.b,A.c,A.d,A.YEAR,a.amount,b.amount
FROM dbo.TB A
left JOIN TB B ON A.a = b.a AND a.b= b.b AND a.c = b.c AND a.d = b.d AND a.YEAR -1 = b.YEAR
/*
abcdYEARamountamount
aabbccdd20122000NULL
aabbccdd201350002000*/