简单select问题,解决马上给分!快帮忙!

forumcsdn 2004-09-07 05:15:35
create table #t(id int, a char)
insert #t values (1, 'a')
insert #t values (2, 'b')
create table #t1(id int, b char)
insert #t1 values (1, 'A')
insert #t1 values (3, 'C')

create table #t2(id int, c char)
insert #t2 values (1, 'B')
insert #t2 values (4, 'B')

要得到结果:
id,a,b,c
1,a,A,B
2,b,null,null
3,null,C,null
4,null,null,B

另外,可能不止三个表的情况,可能有7、8个表,怎么写,没写出来,快帮忙!
...全文
101 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
forumcsdn 2004-09-07
  • 打赏
  • 举报
回复
正确,自已真笨,给分!
zjcxc 2004-09-07
  • 打赏
  • 举报
回复
--或者这样:

select id
,a=max(a)
,b=max(b)
,c=max(c)
from(
select id,a,b=null,c=null from #t
union all
select id,a=null,b,c=null from #t1
union all
select id,a=null,b=null,c from #t2
)a
group by id
forumcsdn 2004-09-07
  • 打赏
  • 举报
回复
我来试试,谢谢
forumcsdn 2004-09-07
  • 打赏
  • 举报
回复
create table #t(id int, a char)
insert #t values (1, 'a')
insert #t values (2, 'b')

create table #t1(id int, b char)
insert #t1 values (1, 'A')
insert #t1 values (3, 'C')

create table #t2(id int, c char)
insert #t2 values (1, 'B')
insert #t2 values (4, 'B')

要得到结果:
列名:id,a,b,c
   ____________
   1,a, A, B
   2,b,null,null
   3,null,C,null
   4,null,null,B

另外,可能不止三个表的情况,可能有7、8个表,怎么写,没写出来,快帮忙!
zjcxc 2004-09-07
  • 打赏
  • 举报
回复
有7,8个表也照样再写下去.
zjcxc 2004-09-07
  • 打赏
  • 举报
回复
--数据
create table #t(id int, a char)
insert #t values (1, 'a')
insert #t values (2, 'b')

create table #t1(id int, b char)
insert #t1 values (1, 'A')
insert #t1 values (3, 'C')

create table #t2(id int, c char)
insert #t2 values (1, 'B')
insert #t2 values (4, 'B')
go

--查询
select id=isnull(a.id,isnull(b.id,c.id))
,a,b,c
from #t a
full join #t1 b on a.id=b.id
full join #t2 c on a.id=c.id
go

--删除测试
drop table #t,#t1,#t2

/*--测试结果

id a b c
----------- ---- ---- ----
1 a A B
3 NULL C NULL
2 b NULL NULL
4 NULL NULL B

(所影响的行数为 4 行)
--*/

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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