2016-06-14 59 views
0

我需要從下面的表(表1)中獲取emp_id,它們已在同一日期加入(joined_date)部門dept1和dept2。以下情況下需要的SQL查詢

emp_id|| department||  joining_date 
1  || dept3  ||  01/01/2014 
1  || dept2  ||  01/01/2015 
1  || dept1  ||  01/01/2015 
2  || dept1  ||  01/01/2015 
2  || dept2  ||  01/03/2015 
3  || dept1  ||  01/02/2015 
3  || dept2  ||  01/02/2015 
3  || dept3  ||  01/02/2015 
4  || dept1  ||  01/01/2014 
4  || dept2  ||  01/01/2014 
5  || dept1  ||  01/01/2014 
5  || dept2  ||  01/01/2015 
5  || dept3  ||  01/01/2016 
6  || dept1  ||  01/01/2014 
6  || dept2  ||  01/01/2014 

所以,我應該得到1,3,4 & 6結果。

+0

使用不同的用EMP_ID –

回答

-1

您可以使用自聯接來獲得結果

select distinct d1.emp_id 
from dept1 d1, 
     dept2 d2 
where d1.department = 'dept1' 
and d2.department = 'dept2' 
and d1.joining_date = d2.joining_date; 
1

內在地運用在同一個表連接。

SELECT `first`.* FROM table1 AS first 
INNER JOIN table1 AS `second` 
     ON `first`.emp_id = `second`.emp_id 
       AND `second`.department = "dept2" 
       AND `second`.joining_date = `first`.joining_date 
WHERE first.department = "dept1" 

例爲DEPT2,你必須添加dept3

+0

它的工作。謝謝Phillip –