【问题标题】: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 Server 2016/17 获取 2 个不同表中的 2 列之间的组合,不包括每列中的值之间的组合?
【发布时间】: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


    【解决方案1】:

    你似乎想要:

    SELECT t1.id, t2.id
    FROM Table1 t1 CROSS JOIN
         Table2 t2;
    

    我不知道您为什么要将所有 id 组合成一个结果集,然后对其进行交叉连接。结果似乎基于一个简单的CROSS JOIN

    【讨论】:

      猜你喜欢
      • 2013-03-31
      • 1970-01-01
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多