只有同时出现两次时,计数才应返回

时间:2018-10-09 06:12:47

标签: sql-server

我想计算员工在场的天数。如果他/她没有超时,则不应考虑他们的出席。

CREATE TABLE Attendance(
[EmpCode] INT
,[TimeIn] DATETIME
,[TimeOut] DATETIME
)
INSERT INTO Attendance VALUES (12,      '2018-08-01 09:00:00.000',      '2018-08-01 17:36:00.000');
INSERT INTO Attendance VALUES (12,      '2018-08-02 09:00:00.000',      NULL);
INSERT INTO Attendance VALUES (12,      '2018-08-03 09:25:00.000',      '2018-08-03 16:56:00.000');
INSERT INTO Attendance VALUES (12,      '2018-08-04 09:13:00.000',      NULL);
INSERT INTO Attendance VALUES (12,      '2018-08-06 09:00:00.000',      '2018-08-07 18:15:00.000');
INSERT INTO Attendance VALUES (12,      '2018-08-07 09:27:00.000',      NULL);

我的查询返回6天,但应该返回3天,因为只有3天同时存在超时和超时。

SELECT 
COUNT(CAST(COALESCE([TimeIn], [TimeOut]) AS DATE))
FROM [dbo].[Attendance]
WHERE
CAST(COALESCE([TimeIn], [TimeOut]) AS DATE) BETWEEN '2018-08-01' AND '2018-08-07'

1 个答案:

答案 0 :(得分:1)

只需添加WHERE条件来检查TimeOut是否为空

SELECT 
    COUNT(CAST(COALESCE([TimeIn], [TimeOut]) AS DATE))
FROM    
    [dbo].[Attendance]
WHERE   
    [TimeOut] is not null
and 
    CAST(COALESCE([TimeIn], [TimeOut]) AS DATE) BETWEEN '2018-08-01' AND '2018-08-07'