嗨,我有以下表格......
A(身份证,姓名) B(ID,姓名) C(ID,姓名)
现在我想获取每个表的名称,这样就不会有跨产品表。即,总行数不会超过最大行表。 如果数据低于
,则为expfor table A id name 1 dilip 2 Amit 3 Piyush 4 sumit for table B id name 1 dilip 4 sumit for table C id name 2 Amit 3 Piyush
然后输出应该如下
nodename_A nodename_B nodename_C Dilip Dilip NULL Amit NULL Amit Piyush NULL Piyush Sumit Sumit NULL
在此表中是基表,它将包含id和node的所有条目,但其他表可能包含较少数量的条目,或者也可能包含重复条目。
请告诉我怎么做?
答案 0 :(得分:0)
在联接中使用FULL JOIN
和COALESCE
:
select nodename_A = A.name
, nodename_B = B.name
, nodename_C = C.name
from A
full join B on A.id = B.id
full join C on coalesce(A.id, B.id) = C.id
order by coalesce (A.id, B.id, C.id)
您可以在此处看到运行代码的示例:
好的,基于我现在假设的新评论:
此新查询适用于上述方案:
select nodename_A = A.name
, nodenameB = case when exists (select 1 from B where A.id = B.id) then A.name end
, nodenameC = case when exists (select 1 from C where A.id = C.id) then A.name end
from A
New SQL Fiddle demo,现在数据中有重复项。
希望现在这对你有用。
答案 1 :(得分:0)
我认为有几个外连接应该这样做:
Select a.name as aName, b.name as bName, c.name as cName
From A
LEFT join B on a.id = b.id
LEFT join C on a.id = c.id
答案 2 :(得分:0)
透视技巧怎么样?
只是一个不同的解决方案..
我想全外连接解决方案更容易阅读
反正..
如果你真的想要在每一行的所有列中使用相同的名称,或者如果不存在则为null
你应该做这样的事情
select *
from( select name as row
,'Table A' as [table]
,name
from [table A]
union all
select name as row
,'Table B' as [table]
,name
from [Table B]
union all
select name as row
,'Table C' as [table]
,name
from [Table C]
)V
PIVOT(max(v.name) for [table] in ([Table A],[Table B],[Table C]))P
order by row
结果集看起来像这样
Table A Table B Table C
Dilip Dilip NULL
Amit NULL Amit
Piyush NULL Piyush
Sumit Sumit NULL
如果您只想要每张桌子上的名单,
相同的名称不需要在同一行..应该做这样的事情
select *
from( select ROW_NUMBER() over (order by name) as row
,'Table A' as [table]
,name
from [table A]
union all
select ROW_NUMBER() over (order by name) as row
,'Table B' as [table]
,name
from [Table B]
union all
select ROW_NUMBER() over (order by name) as row
,'Table C' as [table]
,name
from [Table C]
)V
PIVOT(max(v.name) for [table] in ([Table A],[Table B],[Table C]))P
order by row
结果集看起来像这样
Table A Table B Table C
Amit Dilip Amit
Dilip Sumit Piyush
Piyush NULL NULL
Sumit NULL NULL