如何从多个记录和表中选择结果到一行

时间:2012-12-19 01:10:12

标签: oracle select plsql oracle11g

我有一个特征表,其中包含多个代码和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

我可以得到其中一个,但是我没能在同一行获得第二个

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

2 个答案:

答案 0 :(得分: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 :(得分: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