请考虑下表。
规则是 - 在进入作业编号2之前,员工不能从作业编号1休息(需要退出)。在这种情况下,员工“A”应该在作业1上计时OUT而不是BREAK因为他后来进入了JobNum#2
是否可以编写查询以在纯SQL中找到它?
答案 0 :(得分:1)
这是SQL
select * from employees e1 cross join employees e2 where e1.JOBNUM = (e2.JOBNUM + 1)
and e1.PUNCH_TYPE = 'BREAK' and e2.PUNCH_TYPE = 'IN'
and e1.PUNCHTIME < e2.PUNCHTIME
and e1.EMPLID = e2.EMPLID
答案 1 :(得分:1)
想法是检查下一条记录是否合适。要找到下一条记录,必须找到同一员工当前的第一个打卡时间。一旦检索到该信息,就可以隔离记录本身并检查感兴趣的字段,特别是jobnum是相同的并且[可选地]是punch_type'IN'。如果不是,则不存在计算结果为true并输出记录。
select *
from @punch p
-- Isolate breaks only
where p.punch_type = 'BREAK'
-- The ones having no proper entry
and not exists
(
select null
-- The same table
from @punch a
where a.emplid = p.emplid
and a.jobnum = p.jobnum
-- Next record has punchtime from subquery
and a.punchtime = (select min (n.punchtime)
from @punch n
where n.emplid = p.emplid
and n.punchtime > p.punchtime
)
-- Optionally you might force next record to be 'IN'
and a.punch_type = 'IN'
)
将@punch替换为您的表名。 --
是Sql Server中的注释;如果您不使用此数据库,请删除此行。标记数据库和版本是一个好主意,因为可能有更快/更好的方法来执行此操作。