1

我不确定如何简洁地提出问题来描述我想解决的问题。
我有两个下表:
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 列。

4

3 回答 3

3

这样的事情,应该做

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
于 2012-05-11T10:55:41.923 回答
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
于 2012-05-11T10:57:35.257 回答
0

这就是你所追求的吗?

select tableA.idA as Id, tableA.numA as numA, tableB.numB as numB
from tableA
inner join tableB on tableA.Id = tableB.Id
于 2012-05-11T10:54:47.520 回答