使用多个列的SQL Server连接

时间:2014-03-13 17:33:40

标签: sql sql-server join

我需要帮助在以下场景中加入两个表

Table One
Col A
Col B
Col C1
Col C2
Col C3

Table Two
Col C
Col D

我需要[One]加入[One]并获得One.A和Two.D作为我的输出。

这是连接逻辑:

加入[One] .C1 = [Two] .C如果没有匹配,我需要加入[One] .C2 = Two.C如果没有匹配加入[One] .C3 = [Two] .C

2 个答案:

答案 0 :(得分:2)

您需要COALESCE()

SELECT DISTINCT
    COALESCE(One1.A, One2.A, One3.A) AS A,
    D
FROM
    Two
    LEFT JOIN One AS One1 ON
        Two.C = One1.C1
    LEFT JOIN One AS One2 ON
        Two.C = One2.C2
    LEFT JOIN One AS One3 ON
        Two.C = One3.C3;

答案 1 :(得分:0)

尝试此查询:

SELECT 
one.A as oneA,
two.D as twoD
FROM 
One one
INNER JOIN Two two ON one.C1 = two.C 
OR one.C1 = two.C2 
OR one.C3 = two.C;