首页 > 解决方案 > SQL 显示不等于的记录

问题描述

我们有一个包含 2 列、名称和 check_in_date 的表

每个员工每天都会在每个工作日签到。但是如果我想在特定的一天找出谁没有签到,我该怎么做呢?

select name from table
where check_in_date <> '2021-06-17'

以上对我不起作用,因为它将显示 2021-06-17 之外的记录。我只想查看在该日期未签到的姓名。

提前谢谢了。

标签: sql

解决方案


你需要一张员工表。然后你会使用not exists

select e.*
from employees e
where not exists (select 1
                  from checkins ci
                  where ci.name = e.name and ci.date = ?
                 );

?是您的日期的占位符。

如果您没有单独的表,则可以使用聚合代替:

select name
from checkins
group by name
having sum(case when ci.date = ? then 1 else 0 end) = 0;

推荐阅读