SQL复杂加入if条件

时间:2017-10-12 17:42:50

标签: sql-server join

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

表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非常混乱,所以我要做的是从Table1获取a,b,c,d,e然后将其插入Table2,获取ex2值,再次运行Table2以获得Apple用ex2替换e2,同时留下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

2 个答案:

答案 0 :(得分:2)

只需添加另一个连接到查询,因为左连接遍历额外级别并使用coalesce显示最低级别(如果存在),或者下一个最低级别(如果不存在)。

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

答案 1 :(得分:1)

以下是临时表的示例。

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|
+---------------------+