问题描述
在考勤系统中,很多用户在使用考勤机时,会出现两次以上(clockIn
)和两次以上(clockOut
)的压印错误。所以我有一个表,它获取所有用户的所有记录( ClockIn
和 ClockOut
)“重复”。
我正在寻找一种仅获取 max
的 clockout
和 min
的 clockIn
的方法。
我在 stackoverflow 上看到了这个问题的解决方案:
Get Clock In and clock out time from multiple clock in or multiple clock out in SQL Server
我已经测试过了,它给出了预期的结果,但并非在所有情况下。
1/ 表架构和我创建的选择查询:
就我而言,我有一个包含 employee_records 的表,我只想在同一日期获得一个 ClockIn
和 ClockOut
。
employeerecordId AddAt logtype
我真正需要的是获取两个日期(持续时间)之间的所有时钟输入和时钟输出(同一天只有一个时钟和一个时钟输出)
我该怎么做?
select t.employeeId,MIN(cast(clockIn as time(7))) ClockIn,max(cast(ClockOut as time(7))) clockout
from (select r.employeeId,MIN(cast(r.AddAt as time(7))) clockIn,MAX(cast(r.AddAt as time(7))) clockout,logtype
from emplyee_recoards r
group by r.employeeId,logtype
)t
where CAST(a as date) between @datefrom and @dateto
group by employeeId
创建表并在其上插入数据:
Create table #MyTempTable (employeeId int,addat Datetime,LogType int)
Insert into #MyTempTable values (5005,'2019-05-20 21:35:48.490',1)
Insert into #MyTempTable values (5005,'2019-05-20 22:25:00.000','2019-05-20 06:48:00.000',0)
Insert into #MyTempTable values (5005,'2019-05-20 07:01:15.383','2019-05-25 08:01:15.383','2019-05-25 09:01:15.383','2019-05-25 22:01:15.383','2019-05-25 20:01:15.383',1)
Insert into #MyTempTable values (5006,'2019-05-20 21:25:25.470',1)
Insert into #MyTempTable values (5006,'2019-05-20 23:48:29.568','2019-05-20 08:48:29.568',0)
Insert into #MyTempTable values (5006,'2019-05-20 09:38:29.568',1)
select employeeId,min(Date) Date,min(ClockIn) ClockIn,Max(ClockOut) ClockOut
from (
select employeeId,Min(convert(date,addat)) Date,Min(addat) ClockIn,Max(addat) ClockOut,LogType
from #MyTempTable
Group by employeeId,LogType
having count(convert(date,addat)) > 1
)t
Group by employeeId
Drop table #MyTempTable
将返回:
预期结果:
EmployeeId AddAt ClockIn ClockOut
5005 2019-05-20 2019-05-20 06:48:00.000 2019-05-20 22:25:00.000
5005 2019-05-25 2019-05-25 08:01:15.383 2019-05-25 22:01:15.383
5006 2019-05-20 2019-05-20 08:48:29.568 2019-05-20 23:48:29.568
5006 2019-05-25 2019-05-25 08:01:15.383 2019-05-25 22:01:15.383
解决方法
看起来您想按员工和日期分组,然后使用条件聚合来拆分上班和下班时间。
select
employeeId,convert(date,addat) Date,Min(CASE WHEN LogType = 0 THEN addat END) ClockIn,Max(CASE WHEN LogType = 1 THEN addat END) ClockOut
from #MyTempTable
Group by employeeId,addat)