SQL selection over two rows
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
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'
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)
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
精彩评论