读书人

三表显示有关问题

发布时间: 2013-08-01 15:23:18 作者: rapoo

三表显示问题,在线等
select * from A
select * from B
select * from C
三表显示有关问题

我要这样显示:
A AA B C
1 11 B C
1 11 b1 C1
1 11 B2 null

第一个表只能有一条记录。。但B跟C。可以变。。。
[解决办法]


create table A(A int, AA int)
create table B(B varchar(5), A int)
create table C(C varchar(5), A int)

insert into A
select 1,11

insert into B
select 'B',1 union all
select 'b1',1 union all
select 'B2',1

insert into C
select 'C',1 union all
select 'c1',1


select isnull(t1.A,t2.A) 'A',
isnull(t1.AA,t2.AA) 'AA',
t1.B,
t2.C
from
(select x.A,x.AA,y.B,row_number() over(order by getdate()) 'rn'
from A x left join B y on x.A=y.A) t1
full join
(select x.A,x.AA,z.C,row_number() over(order by getdate()) 'rn'
from A x left join C z on x.A=z.A) t2 on t1.rn=t2.rn

/*
A AA B C
----------- ----------- ----- -----
1 11 B C
1 11 b1 c1
1 11 B2 NULL

(3 row(s) affected)
*/

读书人网 >SQL Server

热点推荐