views:

70

answers:

3

How do I select in a table like below all objects that have a-A and b-B (as key-value pair)?

Something like:

SELECT DISTINCT(OBJECT) 
  FROM MYTABLE 
 WHERE key = 'a' 
   AND value = 'A' 
   AND key = 'b' 
   AND value = 'B'

...where the result would be 1 and 3.

I know that this SQL statement doesn't work, but I hope it explains a bit what I want to do.

And sorry for the diffuse title. I simply don't know how to describe the problem better.

object | key | value
---------------------
1   |  a  |   A
1   |  b  |   B
1   |  c  |   C
2   |  a  |   F
2   |  b  |   B
3   |  a  |   A
3   |  b  |   B
3   |  d  |   D
+4  A: 
select * 
from mytable 
where (key = a and value = a)
or    (key = b and value = b)

or

select * 
from mytable 
where key = a and value = a
union
select * 
from mytable 
where key = b and value = b

or more generally perhaps

select * 
from mytable 
where key = value
and key in (a,b)
Paul Creasey
The problem is that OBJECT must have both a-A and b-B.So your 1st and 3rd statement does not work.The 2nd is maybe a beginning to solve that problem. Now I must take all objects from that result table that occurs exactly two times. The question is how? :-/
Zardoz
maybe HAVING COUNT(*) = 2 but I really do not understand what the problem is with this.
recursive
+3  A: 

I think you want something of this form:

SELECT a.object 
FROM mytable a, mytable b 
WHERE a.object = b.object 
  AND a.key = 'a' AND a.value = 'A'
  AND b.key = 'b' AND b.value = 'B'
Mark E
Thanks a lot. Works great :-)
Zardoz
A: 

You can even try this

declare @t table(object int, keys varchar(10), value varchar(10))
insert into @t 
    select 1,'a','A' union all  select 1,'b','B' union all
            select 1,'c','C' union all  
    select 2,'a','F' union all  select 2,'b','B' union all
    select 3,'a','A' union all  select 3,'b','B' union all
            select 3,'d','D'
--select * from @t 

Query

select object from @t 
where keys = 'a' and value ='A' 
or  keys = 'b'  and value ='B' 
group by object 
having COUNT(object)>1

Output:

object
1
3
biswas.niladri