swwei2002收录,使用标签:SQLSERVER,时间:2008-10-7 16:01:13 | 相关网摘,我也收藏
declare @a table (a int,b int,s int)
declare @b table (a int,b int,c int,d int,m int)
insert @a
select 1,2,20
union all
select 2,3,15
insert @b
select 1,2,3,9,5
union all
select 1,2,4,10,12
union all
select 1,2,5,11,10
union all
select 1,2,6,12,5
union all
select 2,3,4,6,10
union all
select 2,3,5,7,5
union all
select 2,3,6,8,10
select b.a,b.b,b.c,b.d,
case when b.summ-b.m>a.s then b.m else b.summ-a.s end as m
from @a a,(
select x.*,(select sum(m) from @b where a=x.a and b=x.b and d<=x.d) as Summ
from @b x
) b
where a.a=b.a
and a.b=b.b
and b.summ>a.s
http://topic.csdn.net/u/20081006/17/553f30e2-42ad-42fd-a8e2-80e52406f332.html