2016-08-19 120 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