继上一篇https://blog.csdn.net/debimeng/article/details/104113932的思考
假如该公司存放的打卡时间不仅仅上下班两次打卡,还包含了中午外出吃饭打的卡,就是说每个人每天打卡次数大于2次;
这样的话上一篇写的SQL就获取不到准确的上下班时间,
考勤表相关字段如下下:ID、NAME、NO、TIME
ID NAME NO TIME
1 zhangsan 1001 2020-01-01 08:34:40
2 lisi 1002 2020-01-01 08:39:29
3 wangwu 1003 2020-01-01 08:44:38
4 zhangsan 1001 2020-01-01 18:24:18
5 lisi 1002 2020-01-01 18:34:28
6 wangwu 1003 2020-01-01 18:54:20
7 wangwu 1003 2020-01-01 12:34:20
8 wangwu 1003 2020-01-01 12:54:20
日期 姓名 上班时间 下班时间
2020-01-01 zhangsan 2020-01-01 08:34:40 2020-01-01 18:24:18
2020-01-01 lisi 2020-01-01 08:39:29 2020-01-01 18:34:28
2020-01-01 wangwu 2020-01-01 08:44:38 2020-01-01 18:54:20
解决:
select date_format(time,'%Y-%m-%d') as '日期'
,name as '姓名'
,min(time) as '上班时间'
,max(time) as '下班时间'
from tb_cwa
group by name,date_format(time,'%Y-%m-%d')
;
日期 姓名 上班时间 下班时间
2020-01-01 zhangsan 2020-01-01 08:34:40 2020-01-01 18:24:18
2020-01-01 lisi 2020-01-01 08:39:29 2020-01-01 18:34:28
2020-01-01 wangwu 2020-01-01 08:44:38 2020-01-01 18:54:20
备注:建表和数据
create table tb_cwa(id int,name varchar(10),no int,time datetime);
insert into tb_cwa values(1,'zhangsan',1001,'2020-01-01 08:34:40');
insert into tb_cwa values(2,'lisi',1002,'2020-01-01 08:39:29');
insert into tb_cwa values(3,'wangwu',1003,'2020-01-01 08:44:38');
insert into tb_cwa values(4,'zhangsan',1001,'2020-01-01 18:24:18');
insert into tb_cwa values(5,'lisi',1002,'2020-01-01 18:34:28');
insert into tb_cwa values(6,'wangwu',1003,'2020-01-01 18:54:20');
insert into tb_cwa values(7,'wangwu',1003,'2020-01-01 12:34:20');
insert into tb_cwa values(8,'wangwu',1003,'2020-01-01 12:54:20');
来源:CSDN
作者:debimeng
链接:https://blog.csdn.net/debimeng/article/details/104117288