求一条SQL语句 三个表合并

86010088 2006-02-11 10:04:47
合同号 合同金额
-----------------------
1 10000
2 20000

合同金额 已付金额
----------------------
1 6000
2 8000
1 4000
2 12000

合同号 已收金额
------------------------
1 7000.0
2 15000.0
1 3000.0
2 5000.0


如何将上面三个表合成下面这个表
***************************************

合同号 合同金额 已付金额 已收金额
------------------------------------------------------------------------
1 10000 10000 10000
2 20000 20000 20000

...全文
140 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
86010088 2006-02-11
  • 打赏
  • 举报
回复
不好意思,楼上的,分结完了,你的真简单,同样谢谢你
$扫地僧$ 2006-02-11
  • 打赏
  • 举报
回复
create table 表A(合同号 int,合同金额 int)
create table 表B(合同号 int,已付金额 int)
create table 表C(合同号 int,已收金额 int)
insert 表A select 1,10000
insert 表A select 2,20000
insert 表B select 1,6000
insert 表B select 2,8000
insert 表B select 1,4000
insert 表B select 2,12000
insert 表C select 1,7000
insert 表C select 2,15000
insert 表C select 1,3000
insert 表C select 2,5000



select A.合同号,A.合同金额,
(select sum(已付金额) from 表B where 合同号=A.合同号) as 已付金额,
(select sum(已收金额) from 表C where 合同号=A.合同号) as 已收金额
from 表A A
86010088 2006-02-11
  • 打赏
  • 举报
回复
谢谢
zhaoanle 2006-02-11
  • 打赏
  • 举报
回复
--测试数据
create table 表A(合同号 int,合同金额 int)
create table 表B(合同号 int,已付金额 int)
create table 表C(合同号 int,已收金额 int)
insert 表A select 1,10000
insert 表A select 2,20000
insert 表B select 1,6000
insert 表B select 2,8000
insert 表B select 1,4000
insert 表B select 2,12000
insert 表C select 1,7000
insert 表C select 2,15000
insert 表C select 1,3000
insert 表C select 2,5000
go


select a.合同号,a.合同金额,b.已付金额,c.已收金额
from
(select 合同号,sum(合同金额) as '合同金额' from 表A group by 合同号) a
left join
(select 合同号,sum(已付金额) as '已付金额' from 表B group by 合同号) b
on a.合同号=b.合同号
left join
(select 合同号,sum(已收金额) as '已收金额' from 表C group by 合同号) c
on a.合同号=c.合同号
/*结果

合同号 合同金额 已付金额 已收金额
----------- ----------- ----------- -----------
1 10000 10000 10000
2 20000 20000 20000

(所影响的行数为 2 行)

34,592

社区成员

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

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