SQL 复杂地连接了 if 条件



我正在编写一个长查询来收集一些数据。这是一个模拟数据:

表1:

a|b|c|d|e   
1|1|2|2|134  

表2:
A2,B2,C2,D2,E2 是组合键

a2|b2|c2|d2|e2  |f2    |ax2|bx2|cx2|dx2|ex2  
1 |1 |2 |2 |134 |Orange|1  |1  |2  |2  |155  
1 |1 |2 |2 |155 |Apple |Null|Null|Null|Null|Null

我的查询是这样的:

Select * from Table1  
inner join  
Table2 on Table1.a=Table2.a2 and Table1.b=Table2.b2 and Table1.c=Table2.c2 and Table1.d=Table2.d2 and Table1.e=Table2.e2 

这给了我

我需要的答案是

苹果

表 2

非常混乱,所以我要做的是从表 1 中获取 a,b,c,d,e,然后将其插入表 2,获取 ex2 值,再次运行 Table2 以获得 Apple,方法是将 e2 替换为 ex2,同时保持 a2,b2,c2,d2 不变。

就像我提到的,它有点复杂,所以如果您需要,请询问更多详细信息。我试图尽可能多地给予。

我也试过这个(仍然没有快乐):

Select y.a2,y.b2,y.c2,y.d2,(Select case when e2 is not null and ex2 is not null then ex2 else e2 end) from Table1 x inner join Table2 y on x.a=y.a2 and x.b=y.b2 and x.c=y.c2 and x.d=y.d2 and Table1.e=Table2.e2

只需将另一个联接作为左联接添加到查询中,即可遍历额外的级别,并使用合并显示最低级别(如果存在),或者显示下一个最低级别(如果不存在)。

SELECT Coalesce(C.F2, B.F2) as F2
FROM Table1 A
LEFT JOIN TABLE2 B
  on A.a= b.a2
 and A.B = B.B2 
 and A.C = B.C2
 and A.D = B.D2
 and A.E = B.E2
LEFT JOIN TABLE3 C
  on B.Ax2 = C.A2
 and B.Bx2 = C.B2
 and B.Cx2 = C.c2
 and B.Dx2 = C.D2
 and B.Ex2 = C.E2
<</div> div class="one_answers">

下面是一个临时表的示例。

DROP TABLE IF EXISTS #Table1;
CREATE TABLE #Table1 (
    a int not null,
    b int not null,
    c int not null,
    d int not null,
    e int not null,
);
INSERT INTO #Table1 VALUES (1, 1, 2, 2, 134);
DROP TABLE IF EXISTS #Table2;
CREATE TABLE #Table2 (
    a2 int not null,
    b2 int not null,
    c2 int not null,
    d2 int not null,
    e2 int not null,
    f2 nvarchar(10) not null,
    ax2 int null,
    bx2 int null,
    cx2 int null,
    dx2 int null,
    ex2 int null,
    CONSTRAINT PK_Table2 PRIMARY KEY (a2, b2, c2, d2, e2),
);
INSERT INTO #Table2 VALUES
    (1, 1, 2, 2, 134, 'Orange', 1, 1, 2, 2, 155),
    (1, 1, 2, 2, 155, 'Apple', null, null, null, null, null);
SELECT Branch.a2
    , Branch.b2
    , Branch.c2
    , Branch.d2
    , Leaf.e2
    , Leaf.f2
FROM #Table1 AS Root
INNER JOIN #Table2 AS Branch
    ON Root.a = Branch.a2
    AND Root.b = Branch.b2
    AND Root.c = Branch.c2
    AND Root.d = Branch.d2
    AND Root.e = Branch.e2
INNER JOIN #Table2 AS Leaf
    ON Branch.ex2 = Leaf.e2;

结果是

+---------------------+
|a2|b2|c2|d2|e2 |f2   |
+---------------------+
| 1| 1| 2| 2|155|Apple|
+---------------------+

最新更新