搜索pk有一个AND b

时间:2016-06-27 13:59:42

标签: sql sql-server relational-database relationship

我怎样才能实现以下目标: “任何具有现在和已知状态的员工”

我的桌子就像这样

employee
+--------+---------+
| emp_id | name    |
+--------+---------+
| a001   | michael |
+--------+---------+
| a002   | john    |
+--------+---------+

status
+--------+---------+
| emp_id | status  |
+--------+---------+
| a001   | Present |
+--------+---------+
| a001   | Latein  |
+--------+---------+
| a002   | Absence |
+--------+---------+

4 个答案:

答案 0 :(得分:3)

select e.name
from employee e
join status s on s.emp_id = e.emp_id
where s.status in ('Present', 'Latein')
group by e.emp_id, e.name
having count(*) = 2

答案 1 :(得分:2)

一种方法是在状态:

的派生表上使用内部联接
SELECT name
FROM employee E
INNER JOIN
(
    SELECT emp_Id
    FROM status 
    WHERE status IN('Present', 'Latein')
    GROUP BY emp_Id
    HAVING COUNT(*) = 2
) D 
ON E.emp_Id = D.emp_Id  

派生表将仅包含具有PresentLatein记录的员工。

答案 2 :(得分:2)

status表格上使用条件汇总来确定哪些员工有'Present''Latein'。然后将此结果连接到employee表以获取匹配的名称。

SELECT t1.emp_id, t1.name
FROM employee t1
INNER JOIN
(
    SELECT emp_id,
        SUM(CASE WHEN status = 'Present' OR status = 'Latein'
                 THEN 1 ELSE 0 END) AS statusSum
    FROM status
    GROUP BY emp_id
    HAVING statusSum = 2
) t2
    ON t1.emp_id = t2.emp_id

答案 3 :(得分:1)

我认为您正在寻找Latein员工。如果他们迟到,他们必须在场,否则他们不会来并且缺席。 所以对你来说最好使用

SELECT emp_id FROM status WHERE status='Latein'