我正在尝试提取从未参加过培训的员工的数据。有一个列“ Attended”,当员工不参加培训时,他们第二次以“ Attended = 0”进入数据库,但是一旦他们下周参加培训,他们就会在另一行添加内容“参加人数= 1”
当我在Attended = 0的情况下提取数据时,它是在收集从未参加过培训的员工以及错过一次培训但又在下周参加培训的员工的数据。
我如何让那些“参加”从不等于“ 1”但也等于0的员工?
答案 0 :(得分:1)
假设存在一列employeeid
,则可以group by employeeid
并使用聚合来获取表中只有attended = 0
的员工:
select employeeid
from tablename
group by employeeid
having sum(attended) = 0
答案 1 :(得分:0)
您可以使用except
获取除where attended = 0
之外的所有where attended = 1
。不幸的是,MySQL不支持except
,因此我们必须伪造它。
例如...
select *
from attendance;
employee_id training_id attended
----------- ----------- ----------
1 1 0
1 1 1
2 1 0
3 1 1
1 2 0
1 3 1
在此示例中,员工1必须组成培训2,而员工2必须组成培训1。
select employee_id, training_id
from attendance
where attended = 1;
employee_id training_id
----------- -----------
1 1
3 1
1 3
参加培训的每个人。
select employee_id, training_id
from attendance where attended = 0;
employee_id training_id
----------- -----------
1 1
2 1
1 2
就是每个错过训练的人。
通常,您会在此处使用except
来运行两个查询。
select employee_id, training_id
from attendance
where attended = 0
except
select employee_id, training_id
from attendance
where attended = 1;
employee_id training_id
----------- -----------
1 2
2 1
但是MySQL不支持。相反,我们使用left excluding self join来模拟它。
select a1.employee_id, a1.training_id
from attendance a1
-- Self join with everyone who attended
left join attendance a2 on
a1.employee_id = a2.employee_id and
a1.training_id = a2.training_id and
a2.attended = 1
-- Get everyone who was marked as not attending and did not later attend
where a1.attended = 0
and a2.employee_id is null;