简体   繁体   中英

SQL Query on multiple rows

I have a table with 3 columns

ProjectNo | Property | Value
----------+----------+-------
        1 | Manager  | Bob
        1 | Prop1    | foo
        1 | Prop2    | bar
        2 | Manager  | Joe
        2 | Prop1    | Ree
        2 | Prop2    | Mee

I want to run a SQL query that returns the ProjectNo where Manager = "Bob" AND Prop1 = "foo" and Prop2 = "bar"

Result should be 1

You can try:

select ProjectNo from table_name
where (Property = 'Manager' and Value = 'Bob') 
      or (Property = 'Prop1' and Value = 'foo')
      or (Property = 'Prop2' and Value = 'bar')
group by ProjectNo, Property, Value
having count(ProjectNo) = 3
limit 1

One way would be to group by the projectNo and take only those having all 3 conditions for each group

select projectNo
from your_table
group by projectNo
having sum(case when property = 'Manager' and value = 'Bob' then 1 end) > 0
   and sum(case when property = 'Prop1' and value = 'foo' then 1 end) > 0
   and sum(case when property = 'Prop2' and value = 'bar' then 1 end) > 0

You could use a self join pn the table with condition for each separated pair property, value

select  m1.projectNo 
from my_table m1 
inner join my_table m2 on m1.projectNo = m2.projectNo
  AND m2.Property = 'Prop1'
    AND  m2.Value = 'foo'
inner join my_table m23on m1.projectNo = m3.projectNo
    AND m2.Property = 'Prop2'
      AND  m2.Value = 'bar'
WHERE m1.Property = 'Manager'
  AND  m1.Value = 'Bob'

Use PIVOT

FIDDLE DEMO

SELECT ProjectNo FROM
(SELECT ProjectNo, Property, Value FROM mytbl) AS SourceTable
PIVOT (MAX(Value) FOR Property IN ([Manager], [Prop1], [Prop2])) AS PivotTable
WHERE  Manager = 'Bob' AND Prop1 = 'foo' AND Prop2 = 'bar'

Do a GROUP BY , use HAVING to make sure all the 3 properties are there:

select ProjectNo
from tablename
where (Property = 'Manager' and Value = 'Bob') 
   or (Property = 'Prop1' and Value = 'foo')
   or (Property = 'Prop2' and Value = 'bar')
group by ProjectNo
having count(distinct Property) = 3

Alternatively, use INTERSECT :

select ProjectNo from tablename where Property = 'Manager' and Value = 'Bob'
INTERSECT
select ProjectNo from tablename where Property = 'Prop1' and Value = 'foo'
INTERSECT
select ProjectNo from tablename where Property = 'Prop2' and Value = 'bar'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM