2017-10-12 57 views
0

我正在寫一個長查詢來獲取一些數據在一起。這是一個模擬數據:SQL複雜的連接,如果條件

表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是相當弄亂了,還等什麼,我要做的是讓A,B ,c,d,e,然後將它插入到Table2中,得到ex2值,再次運行Table2以通過用ex2替換e2來獲得Apple,同時使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 
+1

你需要給真正的表結構和實際查詢,或者它會很困難提供幫助。 – tommyO

+1

它應該讓你橙色E2在表1和表2中都是134。爲什麼它應該給你155?哦,這是一個層次結構。層次總是隻有1級?如果是的話,再次向table2添加一個連接,如果它可能是n級的,那麼你需要一個遞歸cte或者用於xml路徑來遍歷層次結構。 – xQbert

+0

@xQbert在某些情況下,答案是Apple/Orange。如果你使用表2中的e2,表1會給你橙色。如果你想要蘋果,那麼你需要得到ex2的價值,然後插入e2來獲得蘋果。所以是的,這是一種層次結構。 – SQLserving

回答

2

只需要添加另外加入到查詢的左聯接遍歷額外的一層,使用聚結,顯示的最低水平(如果存在),或者如果沒有,則是最低的。

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

這樣做的工作! – SQLserving

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

你的查詢工作得很好,但是xQbert第一次。非常感激! – SQLserving

+0

左連接,而不是內部incase沒有葉子?就像155上的情況一樣? – xQbert

+0

當然,如果這是你的意圖。這個問題有點難以分辨。 –