2016-05-31 87 views
2
單獨列的值

比方說,我有以下兩個表的表1第3欄的SQL查詢 - 在兩個不同的列

Table 1 

Column1 Column2 Column3 
    1  A  ABC 
    1  B  DEF 
    1  C  DEF 
    1  D  GHI 
    1  E  GHI 
    2  A1  ABC 
    2  B1  DEF 
    2  C1  DEF 
    2  D1  GHI 


Table 2 

Column1 DEF  GHI 
    X  B  D 
    X  C  D 
    X  C  E 
    X  G  D 
    Z  B  D 

兩個值都在表2列,這些列將填入數據在table1.column2中。

現在,我需要寫一個SQL查詢,使得對於表1各組(組基於table1.column1),我能得到表2中其中包括所有的DEF值的所有值在是table2.column2組和所有的GHI值的table2.column3

。例如,對給定表,我的預期的輸出應該只X.由於X具有兩個B和C在柱DEF並且在GHI列中具有D和E。另一方面,Z在DEF列中不包含C

有人可以指導我如何進行,我應該怎麼做呢?

+0

可否請您與相關數據庫(甲骨文我猜)標籤? 'PIVOT'就是你要找的東西。 –

+0

PIVOT在這種情況下會如何幫助我? –

+0

對不起,誤解了你的問題 - 以爲你試圖從t1得到t2 –

回答

2

這看起來很複雜。我認爲你可以從表2回到表1兩次,每次一列。這將獲得每個table1.col1的所有匹配項。

然後,查詢可以聚合結果並檢查所有匹配是否完成。因爲這是兩個維度發生時,having條款需要使用count(distinct)

select t2.col1, t1.col1 
from table2 t2 join 
    table1 tdef 
    on tdef.col3 = 'DEF' and tdef.col2 = t2.def join 
    table1 tghi 
    on tghi.col3 = 'GHI' and tghi.col2 = t2.ghi and tghi.col1 = tdef.col1 join 
    (select sum(case when t1.col3 = 'DEF' then 1 else 0 end) as cnt_def, 
      sum(case when t1.col3 = 'GHI' then 1 else 0 end) as cnt_ghi 
     from table1 t1 
    ) tt1 
    on tt1.col1 = tdef.col1 
group by t2.col1 
having count(distinct tdef.col2) = tt1.cnt_def and 
     count(distinct tghi.col2) = tt1.cnt_ghi; 
+0

謝謝。讓我試試吧! :d –