0

我有十几个具有以下格式的表格:

表格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

关于如何解决这个问题有什么建议吗?

4

3 回答 3

2

我提供了一个完全外连接的解决方案,因为这似乎是一种自然的方法:

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 列上使用索引。

于 2012-05-11T13:16:22.463 回答
1

请试试这个

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

谢谢拉贾特

于 2012-05-11T13:27:11.327 回答
0
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 
于 2012-05-11T12:23:27.483 回答