枢轴技巧怎么样?
只是一个不同的解决方案..
我想完整的外连接解决方案更容易阅读
反正..
如果您真的想要每行的所有列中的名称相同,或者如果不存在则为 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