我有这张桌子:
id id_emp ch_in type date ====================================== 1 1 09:12 attend 2019-08-04 2 1 NULL absent 2019-08-04 3 2 09:20 attend 2019-08-04 4 2 NULL absent 2019-08-04 5 3 NULL absent 2019-08-04 6 1 NULL absent 2019-08-05
我想选择所有缺席的员工ID(id_emp
)。但是,如果该员工已经有一个较早的ch_in
,并且在同一天也不为空,那么他就不会缺席。
因此在示例数据中,结果将是:
结果必须是:
id id_emp ch_in type date ====================================== 5 3 NULL absent 2019-08-04 6 1 NULL absent 2019-08-05
我很累这样做:
select distinct id_emp,ch_in,type,date
FROM ch_inout
where absent= 'absent'
但是我无法使其工作。如何获得正确的结果?
答案 0 :(得分:3)
不存在:
select c.* from ch_inout c
where c.type = 'absent'
and not exists (
select 1 from ch_inout
where id_emp = c.id_emp and date = c.date and ch_in is not null
)
请参见demo。
结果:
> id | id_emp | ch_in | type | date
> -: | -----: | :---- | :----- | :---------
> 5 | 3 | null | absent | 04/08/2019
> 6 | 1 | null | absent | 05/08/2019
答案 1 :(得分:2)
您可以使用GROUP BY
:
SELECT id_emp, date
FROM ch_inout
GROUP BY id_emp, date
HAVING MAX(ch_in) IS NULL