很急,请大家帮帮忙写个查询语句!~非常感谢

SQL147 2005-12-29 02:33:26

tb1:
fh item y_price--(应收款)
a1 电费 100
a1 房租 800
a1 水费 30

tb2:
fh bh item f_price--(付款)
a1 b1 房租 500
a1 b2 房租 200
a1 房租 300
a1 水费 30
tb3:
fh bh item t_price--(退款)
a1 b1 房租 100
a1 b2 房租 100

查询的结果:
fh item y_price f_price t_price 欠款
a1 电费 100 0 100
a1 房租 800 500 100 400
a1 房租 800 200 100 300
a1 房租 800 300 0
a1 水费 30 30 0

...全文
101 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
子陌红尘 2005-12-29
  • 打赏
  • 举报
回复
a1 b1 房租 500
a1 b2 房租 200
a1 房租 300
-------------------------------------------------------------------------------------
以上三条记录怎样确定先后顺序?按照在表里的物理顺序?
mislrb 2005-12-29
  • 打赏
  • 举报
回复
学习
SQL147 2005-12-29
  • 打赏
  • 举报
回复
这样是个办法,但如果TB2中数据很多那查询起来不很慢哦!?
其他方法有么?
lsqkeke 2005-12-29
  • 打赏
  • 举报
回复
难道你就是传说中的厉害
子陌红尘 2005-12-29
  • 打赏
  • 举报
回复
declare @tb1 table(fh varchar(20),item varchar(20),y_price int)
insert into @tb1 select 'a1','电费',100
insert into @tb1 select 'a1','房租',800
insert into @tb1 select 'a1','水费',30

declare @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',' ','水费',30

declare @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','房租',100

declare @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
*/
aassdd 2005-12-29
  • 打赏
  • 举报
回复
好强
SQL147 2005-12-29
  • 打赏
  • 举报
回复
[欠款] =a.y_price-isnull(b.f_price,0)-isnull(c.t_price,0)
不是这样的公式,请再查一下欠款这项数字,谢谢
子陌红尘 2005-12-29
  • 打赏
  • 举报
回复
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

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧