如何使用 SQL Server 2016/17 获取 2 个不同表中 2 列之间的组合,不包括每列中值之间的组合?
How to get the combinations between 2 columns in 2 different tables excluding combinations between values in each column using SQL Server 2016/17?
我想知道如何使用 SQL 服务器 2016 或 2017 获取 2 个不同表中 2 列之间的组合,不包括表 1 中的值之间的组合和表 2 中的值之间的组合?
我需要合并 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
您似乎想要:
SELECT t1.id, t2.id
FROM Table1 t1 CROSS JOIN
Table2 t2;
我不知道您为什么要将所有 ID 合并到一个结果集中,然后对其进行交叉连接。结果似乎基于简单的 CROSS JOIN
.
我想知道如何使用 SQL 服务器 2016 或 2017 获取 2 个不同表中 2 列之间的组合,不包括表 1 中的值之间的组合和表 2 中的值之间的组合?
我需要合并 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
您似乎想要:
SELECT t1.id, t2.id
FROM Table1 t1 CROSS JOIN
Table2 t2;
我不知道您为什么要将所有 ID 合并到一个结果集中,然后对其进行交叉连接。结果似乎基于简单的 CROSS JOIN
.