根据多行和多列选择值

时间:2012-03-06 18:13:02

标签: sql oracle select

我有这张桌子:

id       characteristic      value
 1          color            blue
 1          shape            rectangle
 2          color            green
 2          shape            triangle

我需要根据颜色和形状选择id,例如,我想选择颜色为蓝色且形状为矩形的ID(它只返回值1)。

主键是复合(id +特征),因此没有id将具有多个特征值。

此外,还有可能具有更多或更少的特征。

有人可以帮我解决这个问题吗?

祝你好运

2 个答案:

答案 0 :(得分:2)

SELECT  id
  FROM  MyTable t
        JOIN MyTable t2 ON t.id = t2.id
 WHERE  t.characteristic  = 'color' AND t.value ='blue'
   AND  t2.characteristic = 'shape' AND t2.value='rectangle' --just fixed the t1 to t2

答案 1 :(得分:2)

另一种方法,如果条件数量发生变化,您无需进行太多更改:

with conditions as (
   select 'color' as characterstic, 'blue' as value from dual
   union all 
   select 'shape' as characterstic, 'rectangle' as value from dual
)
select id
from characteristics c2
where (characteristic, value) in ( select characteristic, value from conditions )
group by id
having count(*) = (select count(*) from conditions)

这样你只需要在CTE中添加另一个“行”,不需要改变任何其他内容。

相关问题