【发布时间】:2018-03-14 11:41:24
【问题描述】:
我想知道如何使用 SQL Server 2016 或 2017 获取 2 个不同表中的 2 列之间的组合,不包括 Table1 中的值之间和 Table2 中的值之间的组合?
我需要将 Table1 中的 id2 和 Table2 中的 id 结合起来。
为了得到结果,我使用了这个查询:
WITH CTE AS (
SELECT id2 AS col FROM Table1
UNION
SELECT id AS col FROM Table2
)
SELECT c1.col, c2.col
FROM CTE c1
CROSS JOIN CTE c2
WHERE c1.col < c2.col
ORDER BY c1.col, c2.col
表1
|id |id2|
| 1 | 1 |
| 2 | 2 |
表2
|id |
| 3 |
| 4 |
预期结果
|id |id2|
| 1 | 3 | - correct combination
| 2 | 3 | - correct combination
| 1 | 4 | - correct combination
| 2 | 4 | - correct combination
错误的结果
|id |id2|
| 1 | 3 | - correct combination
| 2 | 3 | - correct combination
| 1 | 4 | - correct combination
| 2 | 4 | - correct combination
| 1 | 2 | - incorrect combination from Table 1
| 3 | 4 | - incorrect combination from Table 2
【问题讨论】:
标签: sql combinations sql-server-2016 sql-server-2017