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

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

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
4

2 回答 2

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
于 2012-12-19T03:24:08.680 回答
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

于 2012-12-19T09:07:55.640 回答