繁体   English   中英

SQL 查询多行

[英]SQL Query on multiple rows

我有一个包含 3 列的表

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

我想运行一个返回ProjectNo的 SQL 查询,其中Manager = "Bob" AND Prop1 = "foo" and Prop2 = "bar"

结果应该是 1

你可以试试:

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

一种方法是按projectNo进行分组,并且每组只采用具有所有 3 个条件的那些

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

您可以使用自联接 pn 表,其中包含每个分隔对属性、值的条件

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'

使用PIVOT

小提琴演示

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'

执行GROUP BY ,使用HAVING确保所有 3 个属性都存在:

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

或者,使用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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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