2016-08-19 115 views
1

这可能是简单的SQL查询。我发现它有点棘手,因为我已经写了一段时间了。基于多行过滤数据SQL

ID NAME  VALUE 
--- ------  ------- 
1 Country  Brazil 
1 Country  India 
2 Country  US 
2 EmpLevel 1 
3 EmpLevel 3 

伪查询:

Select * 
from table_name 
where (country = US or country = Brazil) 
    and (Employee_level = 1 or Employee_level = 3) 

此查询应该返回

ID NAME  VALUE 
--- ------  ------- 
2  Country  US 
2  EmpLevel  1 

(由于记录与ID - 2具有国家为 '美国' 和EmpLevel '1')

我也经历了几个SO帖子。

Multiple row SQL Where clause

SQL subselect filtering based on multiple sub-rows

Evaluation of multiples 'IN' Expressions in 'WHERE' clauses in mysql

回答

1

我假设你预期的country结果应该是US,而不是Brazil。下面是一个使用joinconditional aggregation一个选项:

select y.* 
from yourtable y join (
    select id 
    from yourtable 
    group by id 
    having max(case when name = 'Country' then value end) in ('US','Brazil') and 
     max(case when name = 'EmpLevel' then value end) in ('1','3') 
) y2 on y.id = y2.id 
+0

有点晚了,:)是的,更新的问题按照评论 – mlg