在具有不同名称的列上连接表但在结果中生成单列

时间:2012-05-11 10:50:56

标签: sql sql-server database tsql join

我不确定如何简明地提出问题来描述我想解决的问题 我有两张桌子:
Table 1

[idA] [numA]
 NULL   8
 1      10
 2      15
 3      16

Table 2

[idB] [numB]
 2      14
 3      30
 4      32

现在,我不确定如何制定T-Sql查询以产生以下结果:

[id] [numA] [numB]
NULL  8      0
1     10     0
2     15     14
3     16     30
4     0      32

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

更新:


如果要再加入一个表(idC,numC),@ AdaTheDev的脚本是否会出现任何问题?在那种情况下,什么是最好的解决方案?问题是我有15个要加入到一个表中,它们应该按ID分组并且有15个相应的numX列。

3 个答案:

答案 0 :(得分:4)

这样的事,应该这样做

SELECT ISNULL(t1.idA, t2.idB) AS id, 
    ISNULL(t1.numA, 0) AS numA, 
    ISNULL(t2.NumB, 0) AS numB
FROM table1 t1
    FULL OUTER JOIN table2 t2 ON t1.idA = t2.idB OR t1.ida IS NULL AND t2.idb IS NULL

<强>更新
注意我已经为连接添加了OR条件来处理idA和idB为NULL的情况,以提供单个结果

完整的测试脚本(在table2中添加了NULL id记录):

DECLARE @Table1 TABLE (ida integer, numA INTEGER)
DECLARE @Table2 TABLE (idb integer, numb INTEGER)

INSERT @Table1 ([ida], [numA])
VALUES (NULL, 8), (1, 10), (2, 15), (3, 16)

INSERT @Table2 ([idb], [numb])
VALUES (NULL, 9), (2, 14), (3, 30), (4, 32)

SELECT ISNULL(t1.idA, t2.idB) AS id, 
    ISNULL(t1.numA, 0) AS numA, 
    ISNULL(t2.NumB, 0) AS numB
FROM @table1 t1
    FULL OUTER JOIN @table2 t2 ON t1.idA = t2.idB OR t1.ida IS NULL AND t2.idb IS NULL

答案 1 :(得分:1)

DECLARE @table1 AS TABLE (idA INT, numA INT)
DECLARE @table2 AS TABLE (idB INT, numB INT)

INSERT INTO @table1
VALUES 
(NULL, 8),
(1, 10),
(2, 15),
(3, 16)

INSERT INTO @table2
VALUES
(2, 14),
(3, 30),
(4, 32)


SELECT COALESCE(ida, idb) AS id, ISNULL(numa, 0) AS numa, ISNULL(numb, 0) AS numb
FROM @table1
FULL OUTER JOIN @table2 ON ida = idb

答案 2 :(得分:0)

这就是你要追求的吗?

select tableA.idA as Id, tableA.numA as numA, tableB.numB as numB
from tableA
inner join tableB on tableA.Id = tableB.Id