简体   繁体   中英

How to use Distinct in WHERE clause

I have this query to count the number of presents employee have in a month.

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'

Now there are plenty of employees that have been marked there attendance twice or thrice in one date. Like once an employee leave his attendance is placed as out and once he comes than as timein. So now on counting it is adding same days attendance multiple times. I want to get distinct dates between the dates.

Here is sample data:

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

Now it is counting date 4 two times but it should count it single time.

DISTINCT should be inside the COUNT()

So, it would be :

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

However, i would suggest to use proper standard, explicit JOIN syntax instead of comma in FROM clause :

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'

Try this to cast to date and perform the distinct

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM