2012-12-19 38 views
0

我有一個特性表,其中包含一個ID的多個代碼和值,以及一個對每個代碼和值都有相應描述的查找表。我想從兩個表中選擇一個ID,descr1,descr2,其中第一個descr用於一個查找代碼/值對,而descr用於另一個。例如:如何從多個記錄和表中選擇結果到一行中

Table1 
ID Code Value 
1 Color 1 
1 Tone 4 
1 Type Poor 
2 Color 3 
2 Tone 4 


Table2 
Code Value Descr 
Color 1  Red 
Color 2  Blue 
Color 3  Yellow 
Tone 4  Clear 
Type Good Used, but good condition 
Type New New 
Type Poor Used, poor condition 

我希望能夠查詢ID 1,並得到了顏色和類型,並因此獲得了創紀錄的像

ID Color Type 
1 Red  Used, poor condition 

我可以得到其中的一個,但我m,在獲得第二次在同一行

select t1.ID, t2.Descr as Color 
from Table1 t1 
join Table2 t2 
    on t1.Code = t2.Code 
and t1.Value = t2.Value 
where t1.ID = 1 
and t1.Code = (select t2b.Code 
       from Table2 t2b 
       where t1.Code = t2b.Code 
        and t1.Value = t2b.Value 
        and t1.Value = 'Color') 

我想我會了解這一切錯了,我一直在尋找的失敗 - 我敢肯定,這個問題已經被問過,但我沒有找到它。有時候,您需要知道查詢類型中使用的詞語,以便能夠找到關於您正在嘗試執行的操作的幫助。

更新 我把GKV和knagaev的答案結合起來,因爲max和case一起給了我我正在尋找的東西。這給了我想要的東西:

select t1.ID 
     ,max((case when t1.Code='Color' then t2.Descr else null end)) as Color 
     ,max((case when t1.Code='Type' then t2.Descr else null end)) as Type 
from Table1 t1,Table2 t2 
where t1.Code = t2.Code and t1.Value = t2.Value 
    and t1.ID = 1 
group by t1.ID 
+0

那麼,我該怎麼辦,當我需要兩個答案結合起來,得到解決?我選擇了誰的答案? – thursdaysgeek

回答

2

只使用 「標準」 的Oracle SQL

select t1.id, 
    max(decode (t1.code, 'Color', t2.descr, null)) color, 
    max(decode (t1.code, 'Tone', t2.descr, null)) tone, 
    max(decode (t1.code, 'Type', t2.descr, null)) type 
from table1 t1, table2 t2 
where t1.code = t2.code 
    and t1.value = t2.value 
    and t1.id = 1 
group by t1.id 

SQLFiddle

4

只是簡單的連接將與​​字符串連接一起完成工作。 有點像這個

select t1.ID 
    ,wm_concat(case when t1.Code='Color' then t2.Descr else null end) as Color 
    ,wm_concat(case when t1.Code='Type' then t2.Descr else null end) as Type 
    from Table1 t1,Table2 t2 
    where t1.Code = t2.Code and t1.Value = t2.Value 
     and t1.ID = 1 
    group by t1.ID 
+1

wm_concat沒有記錄。 OP應該在11g上使用listagg而不是 –

+0

我不希望這些字段合併,我只是想讓它們在一個記錄中。所以wm_concat或listagg是不必要的。 – thursdaysgeek

+0

@thursdaysgeek 我剛剛使用字符串連接作爲 null + string = string ...這是我寫字符串連接後的想法... – GKV

相關問題