select
a.fh,
a.item,
a.y_price,
f_price=isnull(b.f_price,0),
t_price=isnull(c.t_price,0),
[欠款] =a.y_price-isnull(b.f_price,0)-isnull(c.t_price,0)
from
tb1 a
left join
tb2 b
on
a.fh=b.fh and a.item=b.item
left join
tb3 c
on
a.fh=c.fh and a.item=c.item and b.bh=c.bh
a.fh,
a.item,
a.y_price,
f_price=isnull(b.f_price,0),
t_price=isnull(c.t_price,0),
[欠款] =a.y_price-isnull(b.f_price,0)-isnull(c.t_price,0)
from
tb1 a
left join
tb2 b
on
a.fh=b.fh and a.item=b.item
left join
tb3 c
on
a.fh=c.fh and a.item=c.item and b.bh=c.bh
不是这样的公式,请再查一下欠款这项数字,谢谢
insert into @tb1 select 'a1','电费',100
insert into @tb1 select 'a1','房租',800
insert into @tb1 select 'a1','水费',30declare @tb2 table(fh varchar(20),bh varchar(20),item varchar(20),f_price int)
insert into @tb2 select 'a1','b1','房租',500
insert into @tb2 select 'a1','b2','房租',200
insert into @tb2 select 'a1',' ','房租',300
insert into @tb2 select 'a1',' ','水费',30declare @tb3 table(fh varchar(20),bh varchar(20),item varchar(20),t_price int)
insert into @tb3 select 'a1','b1','房租',100
insert into @tb3 select 'a1','b2','房租',100declare @tb4 table(id int identity(1,1),fh varchar(20),bh varchar(20),item varchar(20),f_price int)
insert into @tb4 select * from @tb2
select
a.fh,
a.item,
a.y_price,
f_price=isnull(b.f_price,0),
t_price=isnull(c.t_price,0),
[欠款] =a.y_price-isnull((select
sum(e.f_price-isnull(f.t_price,0))
from
@tb4 e
left join
@tb3 f
on
e.fh=f.fh and e.item=f.item and e.bh=f.bh
where
e.item=b.item and e.fh=b.fh and e.id<=b.id),0)
from
@tb1 a
left join
@tb4 b
on
a.fh=b.fh and a.item=b.item
left join
@tb3 c
on
a.fh=c.fh and a.item=c.item and b.bh=c.bh
/*
fh item y_price f_price t_price 欠款
-------------------- -------------------- ----------- ----------- ----------- -----------
a1 电费 100 0 0 100
a1 房租 800 500 100 400
a1 房租 800 200 100 300
a1 房租 800 300 0 0
a1 水费 30 30 0 0
*/
a1 b2 房租 200
a1 房租 300
-------------------------------------------------------------------------------------
以上三条记录怎样确定先后顺序?按照在表里的物理顺序?