[英]Joining multiple tables into one under one Id
我有许多具有以下格式的表:
表格1
[idA] [numA]
NULL 8
1 10
2 15
3 16
表2
[idB] [numB]
2 14
3 30
4 32
表3
[idC] [numC]
NULL 56
1 24
4 37
5 36
...
现在,我不确定如何制定T-Sql查询以产生以下结果:
[id] [numA] [numB] [numC] ...
NULL 8 0 56
1 10 0 24
2 15 14 0
3 16 30 0
4 0 32 37
5 0 0 36
关于如何解决这个问题有什么建议吗?
我提供了具有完全外部联接的解决方案,因为这似乎是自然的方法:
SELECT coalesce(a.id, b.id, c.id, . . .) as id,
a.NumA, b.NumB, c.NumC, . . .
FROM TableA a full outer join
TableB b
on a.id = b.id full outer join
TableC c
on coalesce(a.id, b.id) = c.id
但是,需要仔细编写查询,以使合并保持一致。 这种方法的一个优点是,它应该在查询的id列上使用索引。
请尝试这个
select id, max(numa),max(numb),max(numc) from
(
select id,numa,0 as numb,0 as numc from tb1
union all
select id,0 as numa,numb as numb,0 as numc from tb2
union all
select id,0 as numa,0 as numb,numc as numc from tb3
)X
group by id
order by id
感谢Rajath
SELECT Maintable.id,
Table1.numA,
Table2.numB,
Table3.numC
FROM (SELECT ida AS id
FROM Table1
UNION
SELECT idb AS id
FROM Table2
UNION
SELECT idc AS id
FROM Table3) MainTable
LEFT JOIN Table1
ON Maintable.id = Table1.Ida
LEFT JOIN Table2
ON Maintable.id = Table2.idB
LEFT JOIN Table3
ON Maintable.id = Table3.idC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.