日期:2014-05-17 浏览次数:20719 次
-- 测试数据:#
if object_id('tempdb.dbo.#') is not null drop table #
create table #(a varchar(8), b date, c int, d int)
insert into #(a,b,c)
select '002', '2002-01-30', 1000 union all
select '002', '2002-02-28', 1500 union all
select '002', '2003-04-30', 2800 union all
select '002', '2003-05-30', 3000 union all
select '003', '2003-04-30', 2800 union all
select '003', '2003-05-30', 3000
update a set a.d = a.c-isnull(b.c,0) from # a left join # b on a.a=b.a and year(a.b)=year(b.b) and month(a.b)=month(b.b)+1
select * from #
/*
a b c d
-------- ---------- ----------- -----------
002 2002-01-30 1000 1000
002 2002-02-28 1500 500
002 2003-04-30 2800 2800
002 2003-05-30 3000 200
003 2