连接两个列表,列中显示每个表中没有重复项的值

时间:2018-01-25 04:24:52

标签: sql sql-server tsql sql-server-2014

我有两张桌子。每个表有两列。每个表的第一列是匹配/映射列。我不知道如何解释我想要做什么,所以我将使用一个例子。

表1

| col1 | col2  |
|------|-------|
| a    | one   |
| a    | two   |
| b    | three |
| c    | four  |

表2

| col1 | col2  |
|------|-------|
| a    | five  |
| b    | six   |
| b    | seven |
| d    | eight |

期望的输出

| col1 | table1 | table2 |
|------|--------|--------|
| a    | one    | five   |
| a    | two    |        |
| b    | three  | six    |
| b    |        | seven  |
| c    | four   |        |
| d    |        | eight  |

(空单元格为空)

基本上我正在寻找一个汇总表,其中显示了每个表中col2的所有col1选项。我希望这是有道理的......

1 个答案:

答案 0 :(得分:2)

您需要FULL OUTER JOINROW_NUMBER

SELECT COALESCE(a.col1, b.col2),
       COALESCE(a.col2, ''),
       COALESCE(b.col, '')
FROM   (SELECT *,
               Rn = Row_number()OVER(partition BY col1 ORDER BY @@SPID)
        FROM   table1) a
       FULL JOIN (SELECT *,
                         Rn = Row_number()OVER(partition BY col1 ORDER BY @@SPID)
                  FROM   table2) b
              ON a.col1 = b.col1
                 AND a.Rn = b.Rn