根据多行SQL

时间:2016-08-19 04:15:20

标签: sql sql-server

这可能是简单的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的记录,Country为'US',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 个答案:

答案 0 :(得分:1)

我认为您country的预期结果应该是US而不是Brazil。这是使用join conditional 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