create table aa
(
hth int,
ze int
)
go
insert aa(hth,ze) values(1,456)
insert aa(hth,ze) values(2,387)
go
create table bb
(
hth int,
xh int,
je int
)
go
insert bb select 001 , 1 , 34
union all select 001 , 2 , 66
union all select 001 , 3 , 50
union all select 002 , 1 , 20
union all select 002 , 2 , 10
select b.*,aa.ze-(select sum(je) from bb where hth=b.hth and xh<=b.xh ) from bb b,aa where b.hth=aa.hth
declare @a table (hth varchar(3), ze int)
declare @b table (hth varchar(3), xh int, je int)
insert into @a
select '001', 456 union select '002', 378
insert into @b
select '001', 1, 34 union select '001', 2, 66 union select '001', 3, 50
union select '002', 1, 20 union select '002', 2, 10
select * from @a
select * from @b
select a.hth, b.xh, b.je,
a.ze - (select sum(je) from @b where hth = a.hth and xh <= b.xh) as ye
from @a a inner join @b b on a.hth = b.hth
order by a.hth, b.xh
insert into @a select '001', 456
insert into @a select '002', 387
insert into @b select '001', 1, 34
insert into @b select '001', 2, 66
insert into @b select '001', 3, 50
insert into @b select '002', 1, 20
insert into @b select '002', 2, 10
--解决方法
select d.hth,xh,d.je,ye=a.je-d.num from @a a inner join (
select *,num=(select sum(c.je) from @b c where b.hth=c.hth and c.xh<=b.xh) from @b b)d
on a.hth=d.hth
create table #a(
hth int,
ze int
)
create table #b(
hth int,
xh int,
je int
)
insert into #a
select 1,456 union all
select 2,387
insert into #b
select 1,1,34 union all
select 1,2,66 union all
select 1,3,50 union all
select 2,1,20 union all
select 2,2,10
select #a.hth,b.xh,b.je,(select #a.ze-(select sum(je) from #b where b.hth=#b.hth and b.xh>=#b.xh)) as ye
from #a,#b as b
where #a.hth=b.hth