2012-12-19 2 views
0

ID에 대한 여러 코드와 값이있는 특성 테이블과 각 코드와 값에 해당하는 설명 테이블이 있습니다. 첫 번째 descr이 하나의 조회 코드/값 쌍에 대한 두 테이블에서 descr1, descr2라는 ID를 선택하고 다른 하나는 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 Color Type 
1 Red  Used, poor condition 

같은 기록을 ID 1 쿼리 및 색상 및 종류를 얻을, 그래서 얻을 수 있도록하려면,하지만 난 ' 같은 행

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') 

내가 잘못 모두에 대해거야 생각하고, 내가 찾고 있었어요에서 두 번째를 얻기에 실패 m -이 질문은 이미 요청 확신 해요,하지만 난 그것을 찾지 못했습니다. 때로는 수행하려는 작업에 대한 도움말을 찾을 수 있도록 쿼리 유형에 사용 된 단어를 알아야합니다. 최대 케이스가 함께 내가 찾던 내게 준 때문에

업데이트 나는, GKV 및 knagaev에서 답을 결합했다. 이것은 내가 원하는 것을 나에게 주었다.

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

같은

그래서
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

단순한 조인은 문자열 연결과 함께 작업을 수행 할 것이다. 다소 전용 "표준"오라클 SQL 사용이

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

관련 문제