我有两张桌子。每个表有两列。每个表的第一列是匹配/映射列。我不知道如何解释我想要做什么,所以我将使用一个例子。
| col1 | col2 |
|------|-------|
| a | one |
| a | two |
| b | three |
| c | four |
| 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
选项。我希望这是有道理的......
答案 0 :(得分:2)
您需要FULL OUTER JOIN
和ROW_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