示例数据:
Id | SwipeTime | SwipeStatus | Invalid_message
----+-------------------------+-------------+-----------------
100 | 2018-04-07 02:45:12.290 | Invalid | 1st Attempt
100 | 2018-04-07 02:45:14.290 | Invalid | 2nd Attempt
100 | 2018-04-07 02:45:21.290 | Valid | NA
100 | 2018-04-07 18:01:51.980 | Valid | NA
101 | 2018-04-07 02:55:12.290 | Invalid | 1st Attempt
101 | 2018-04-07 02:55:14.290 | Invalid | 2nd Attempt
101 | 2018-04-07 18:01:51.980 | Valid | NA
DDL:
DECLARE @tbl TABLE
(
Id INT,
SwipeTime DATETIME,
SwipeStatus VARCHAR(10),
Invalid_message VARCHAR(20)
);
INSERT INTO @tbl
VALUES (100, '2018-04-07 02:45:12.290', 'Invalid', '1st Attempt'),
(100, '2018-04-07 02:45:14.290', 'Invalid', '2nd Attempt'),
(100, '2018-04-07 02:45:21.290', 'Valid', 'NA'),
(100, '2018-04-07 18:01:51.980', 'Valid', 'NA'),
(101, '2018-04-07 02:55:12.290', 'Invalid', '1st Attempt'),
(101, '2018-04-07 02:55:14.290', 'Invalid', '2nd Attempt'),
(101, '2018-04-07 18:01:51.980', 'Valid', 'NA');
员工100的工作时间为2.45,并尝试滑动2次,但没有成功(无效)。但是他第三次刷卡成功了。他去上班,在6点左右扫荡。
101名员工以2.55的价格上班,两次刷卡,但没有成功。他仍然去上班,在6点左右扫荡。
我想在某个特定的日子吸引101名员工。也就是说,在特定的一天中,以员工第一次无效尝试的时间戳记,检查员工在首次尝试无效的5分钟内是否进行了有效尝试。如果没有,我们希望在输出中提供他的详细信息。
可以通过单个选择查询完成此操作吗?由于我无法编写单个查询,因此我现在正在编写执行此操作的过程。但是如果可以在单个查询中完成,我将非常喜欢它。
答案 0 :(得分:3)
尝试此查询:
样本数据:
declare @tbl table (Id int, SwipeTime datetime, SwipeStatus varchar(10), Invalid_message varchar(20));
insert into @tbl values
(100,'2018-04-07 02:45:12.290','Invalid','1st Attempt'),
(100,'2018-04-07 02:45:14.290','Invalid','2nd Attempt'),
(100,'2018-04-07 02:45:21.290','Valid','NA'),
(100,'2018-04-07 18:01:51.980','Valid','NA'),
(101,'2018-04-07 02:55:12.290','Invalid','1st Attempt'),
(101,'2018-04-07 02:55:14.290','Invalid','2nd Attempt'),
(101,'2018-04-07 18:01:51.980','Valid','NA');
T-SQL:
select id from @tbl t
where Invalid_message = '1st Attempt'
and not exists(select 1 from @tbl
where id = t.id
and SwipeStatus = 'Valid'
and SwipeTime between t.SwipeTime and dateadd(minute, 5, t.SwipeTime))