如何在WHERE子句中使用Distinct

时间:2018-08-29 18:37:30

标签: sql sql-server

我有这个查询来统计员工一个月内在场的礼物数量。

SELECT DISTINCT 
    COUNT([Attendance].[Status])
FROM
    [HRM].[tbl_EmployeeAttendance] [Attendance], [HRM].[tbl_EmployeeInfo] [Info]
WHERE 
    [Attendance].[Status] IN ('Early Left', 'Present', 'Half Day', 'Late In')
    AND [Info].[ID] = [Attendance].[EmpCode] 
    AND [Attendance].[EmpCode] = 266 
    AND CAST([Attendance].[AttendanceTimeIn] AS DATE) >= '2018-08-01' 
    AND CAST([Attendance].[AttendanceTimeOut] AS DATE) <= '2018-08-15'

现在有很多员工被标记为两次或三次出席。就像一旦雇员离职,他的出勤就被安排成一次外出,而一旦他来就比按时来待。因此,现在可以算是增加了同一天的出勤次数。我想获得日期之间的不同日期。

以下是示例数据:

2018-04-04 18:12:30  2018-04-04 19:38:12   266  Present
2018-04-04 09:43:01  2018-04-04 09:58:41   266  Present
2018-04-05 16:40:52  2018-04-05 18:40:52   266  Present
2018-04-06 11:35:59  2018-04-06 11:48:49   266  Present

现在它是两次对日期进行4次计数,但应该将其单次计数。

2 个答案:

答案 0 :(得分:3)

DISTINCT应该在COUNT()

所以,应该是:

SELECT COUNT(DISTINCT [Attendance].[Status]), 
       COUNT(DISTINCT CAST([Attendance].[AttendanceTimeIn] AS Date))
. . .

但是,我建议使用正确的标准,显式JOIN语法,而不要使用FROM子句中的逗号:

SELECT COUNT(DISTINCT [Attendance].[Status]),
       COUNT(DISTINCT CAST([Attendance].[AttendanceTimeIn] AS Date))
FROM [HRM].[tbl_EmployeeAttendance] [Attendance] INNER JOIN
     [HRM].[tbl_EmployeeInfo] [Info]
     ON [Info].[ID] = [Attendance].[EmpCode] 
WHERE [Attendance].[Status] IN ('Early Left', 'Present', 'Half Day', 'Late In') AND 
      [Attendance].[EmpCode] = 266 AND 
      CAST([Attendance].[AttendanceTimeIn] AS DATE) >= '2018-08-01'AND 
      CAST([Attendance].[AttendanceTimeOut] AS DATE) <= '2018-08-15'

答案 1 :(得分:1)

尝试使用此方法来投放日期并执行与众不同的

SELECT COUNT(DISTINCT CAST([Attendance].[AttendanceTimeIn] as Date))
FROM [HRM].[tbl_EmployeeAttendance] [Attendance], [HRM].[tbl_EmployeeInfo] [Info]
WHERE [Attendance].[Status] IN ('Early Left', 'Present', 'Half Day', 'Late In')
AND [Info].[ID] = [Attendance].[EmpCode] AND [Attendance].[EmpCode] = 266 
AND CAST([Attendance].[AttendanceTimeIn] AS DATE) >= '2018-08-01' 
AND CAST([Attendance].[AttendanceTimeOut] AS DATE) <= '2018-08-15'