2017-05-16 168 views
1

我要合併這兩個查詢:SQL連接多個

查詢1 - 一個簡單的內部聯接,其中查詢:

Select t1.c1, t1.c2, t1.c3, t2.c1 

from s1.t2 t2 
inner join s1.t1 t1 on t2.c6 = t1.c6 

where t2.c5 >= '2014-01-01' 
and t2.c5 >= '2014-01-01' 
and t1.c4 = 'P' 

這返回一個表,當然,4列。讓我畫出來的位置:

+----+----+----+-------+ 
| C1 | C2 | C3 | T2.C1 | 
+----+----+----+-------+ 
| | | |  | 

查詢2 - 有了,那麼「由分區」語句刪除與複製:

WITH all_col1 (ONE, TWO) AS 
(
    SELECT col1, col2 
    FROM Schema1.Table1 
    UNION 
    SELECT col1, col2 
    FROM Schema2.Table2 
    UNION 
    SELECT col1, col2 
    FROM Schema2.Table3 
) 
SELECT * 
FROM (
    SELECT ONE, TWO, 
    ROW_NUMBER() OVER(PARTITION BY ONE ORDER BY ONE) duplicate_count 
    FROM all_col1 
) all_col1_w_duplicat_count 
WHERE duplicate_count = 1 

這將返回兩列,以去掉,(這意味着所有重複如果第1列有重複多餘的行被顯式刪除):

+-----+-----+ 
| ONE | TWO | 
+-----+-----+ 
|  |  | 

所以我想看到的是第一個查詢和第二查詢合併這樣的,其中兩個被添加到表,其中ONE matches C1:

+------+----+----+-------+-----+ 
| C1 | C2 | C3 | T2.C1 | TWO | 
|(ONE) | | |  |  | 
+------+----+----+-------+-----+ 
|  | | |  |  | 

所以,我試過了INTERSECT,添加了佔位符行。返回空。

我試圖讓查詢1 CTE,然後加入兩個 - 得到了無數的錯誤嘗試。

這裏是我已經能夠拿出這麼迄今爲止最好的 - 在查詢2中的SELECT語句中加入查詢1:

--ALL COL1 WITH beginning 

WITH all_col1 (ONE, TWO) AS 
(
    SELECT col1, col2 
    FROM Schema1.Table1 
    UNION 
    SELECT col1, col2 
    FROM Schema2.Table2 
    UNION 
    SELECT col1, col2 
    FROM Schema2.Table3 
) 


--ALL COL1 SELECT duplicate_count 

SELECT * 
FROM (
    SELECT ONE, TWO, 
    ROW_NUMBER() OVER(PARTITION BY ONE ORDER BY ONE) duplicate_count 
    FROM all_col1 


    -- added join opperation 

    join (


     --SELECT from query 1 

     Select t1.c1, t1.c2, t1.c3, t2.c1 

     from s1.t2 t2 
     inner join s1.t1 t1 on t2.c6 = t5.c6 

     where t2.c5 >= '2014-01-01' 
     and t2.c5 >= '2014-01-01' 
     and t1.c4 = 'P' 


    -- finish join opperation 

    ) as query1 
    on all_col1.ONE = query1.c1 -- <----MOST IMPORTANT PART 


-- finsih ALL COL1 

) all_col1_w_duplicat_count 
WHERE duplicate_count = 1 

此,不幸的是,不給我,結果加入了每個查詢的第一列正在試圖詢問on all_col1.ONE = t1.c1

相反,它似乎只是給了我WITH ALL_col1。

我對sql幾乎一無所知,爲了正確地將這兩個查詢連接在一起,我需要學習什麼?

+0

能否請你告訴樣本數據和預期的效果?我無法按照您的要求單獨處理查詢...... – Siyual

+0

您的第二個查詢方式過於複雜。 'UNION'刪除重複項。 –

+0

@Siyual對不起,我應該第一次添加這些視覺效果。我現在加了他們。 –

回答

1

考慮由兩個派生表(子查詢FROMJOIN條款)爲您的副本計數加盟包括兩個表,而不是隻有一個:

... 
SELECT q.c1, q.c2, q.c3, q.t2_c1, a.[TWO] 
FROM 
    (
    SELECT * 
    FROM (
      SELECT ONE, TWO, 
      ROW_NUMBER() OVER(PARTITION BY ONE ORDER BY ONE) duplicate_count 
      FROM all_col1 
     ) sub 
    WHERE sub.duplicate_count = 1 
) a 

INNER JOIN 
    (
    SELECT t1.c1, t1.c2, t1.c3, t2.c1 as t2_c1 
    FROM s1.t2 t2 
    INNER JOIN s1.t1 t1 on t2.c6 = t5.c6 
    WHERE t2.c5 >= '2014-01-01' 
    AND t2.c5 >= '2014-01-01' 
    AND t1.c4 = 'P' 
) q 

ON a.ONE = q.c1