-- 测试数据:#
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', 3000update 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 2003-04-30 2800 2800
003 2003-05-30 3000 200
*/
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', 3000update 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 2003-04-30 2800 2800
003 2003-05-30 3000 200
*/
go
create table [tb]([a] varchar(3),[b] datetime,[c] int)
insert [tb]
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
goselect t.*,
d=c-isnull((select c from tb where a=t.a and datediff(mm,b,t.b)=1),0)
from tb t/**
a b c d
---- ----------------------- ----------- -----------
002 2002-01-30 00:00:00.000 1000 1000
002 2002-02-28 00:00:00.000 1500 500
002 2003-04-30 00:00:00.000 2800 2800
002 2003-05-30 00:00:00.000 3000 200
003 2003-04-30 00:00:00.000 2800 2800
003 2003-05-30 00:00:00.000 3000 200(6 行受影响)
**/
update x set x.d = x.c-isnull(y.c,0) from # as x left join # as y on x.a=y.a and year(x.b)=year(y.b) and month(x.b)=month(y.b)+1understand?
'20093102','2007-01-01','104000000','2007-01-01','2007-01-31'
'20093102','2007-01-01','104000401','2007-02-01','2007-09-30'
'20093102','2007-01-01','104000401','2007-10-01','9999-12-31'