2016-06-14 60 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 –