两个表联合查询问题

duizhang22 2009-07-26 10:44:44
table a
NO1 M_money
001 50
002 100

table b
NO2 f_money
001 100
003 200
要求结果:
NO M_money f_money
001 50 100
002 100 0
003 0 200

就是要求把两个表里的代表号码的两列(NO1,NO2)中的不重复内容统计到结果的NO里面,然后按照NO排列
其它的字段都跟在后面,没有的地方就是0.
希望有高手帮忙解答一下!!
...全文
38 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
华夏小卒 2009-07-26
  • 打赏
  • 举报
回复


declare @a TABLE (NO1 varchar(10),m_money int )
declare @b TABLE (NO2 varchar(10),f_money int )

insert @a
SELECT '001',50 UNION ALL
SELECT '002',100

insert @b
SELECT '001',100 UNION ALL
SELECT '003',200


select
no= case when a.no1 is null then b.no2 else a.no1 end,
m_money=case when a.m_money is null then 0 else a.m_money end,
f_money=case when b.f_money is null then 0 else b.f_money end
from @a a
right join @b b
on a.no1=b.no2
union
select
no= case when a.no1 is null then b.no2 else a.no1 end,
m_money=case when a.m_money is null then 0 else a.m_money end,
f_money=case when b.f_money is null then 0 else b.f_money end
from @a a
left join @b b
on a.no1=b.no2

/*
no m_money f_money
001 50 100
002 100 0
003 0 200
*/
feixianxxx 2009-07-26
  • 打赏
  • 举报
回复
-- =========================================
-- -----------t_mac 小编-------------
---希望有天成为大虾----
-- =========================================

IF OBJECT_ID('a') IS NOT NULL
DROP TABLE a
GO
CREATE TABLE a(NO1 varchar(10),m_money int )
go
insert a SELECT '001',50
UNION ALL SELECT '002',100
go
IF OBJECT_ID('b') IS NOT NULL
DROP TABLE b
GO
CREATE TABLE b(NO2 varchar(10),f_money int )
go
insert b SELECT '001',100
UNION ALL SELECT '003',200
go
select NO,MAX(m_money) as m_money,MAX(f_money) as f_money
from(
select no=NO1,m_money,f_money=0 from a
union all
select no=NO2,m_money=0,f_money from b) t
group by no
go
/*------------
NO m_money f_money
---------- ----------- -----------
001 50 100
002 100 0
003 0 200

(3 行受影响)
-------*/
lvveve 2009-07-26
  • 打赏
  • 举报
回复
职业帮顶!

34,588

社区成员

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

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