SQL COUNT赋予相同的值

时间:2019-12-06 20:57:11

标签: mysql sql

我有一张看起来像这样的桌子...

 Attendance_ID   person_ID  Meeting_ID  date
---------------  ---------  ----------  ----------
             23         25         123  2013-03-21
             24         25         456  2013-03-21
             25         25         789  2013-03-21
             26         13         147  2013-03-21
             27         25         123  2013-03-22
             28         82         147  2013-03-22
             29         82         456  2013-03-22
             30         13         147  2013-03-23
             31         25         456  2013-03-23
             32         13         456  2013-03-24
             33         25         456  2013-03-28

目标是打印出员工白天错过一次或多次会议的所有时间。我已经尝试了以下查询,但是对于所有日期它给我相同的结果2 ...

SELECT
    replace(replace(dayname(date),"Saturday", "Weekend"),"Sunday", "Weekend") AS day,
    count(distinct personID) AS absences
from
    AttendanceRecord
GROUP BY
    day;

应该在哪里...

Friday   2
Thursday 3
Weekend  3

我要去哪里错了?任何帮助都将受到欢迎,因为我的SQL技能有点生锈。谢谢!

这是MySQL,上面的表格是缺勤的日期。因此,如果受雇者错过了会议123,他们将出现在此桌子上。该查询用于查看当天错过会议的员工数量。

2 个答案:

答案 0 :(得分:0)

count(distinct personID) AS absences

应该是

count(distinct employeeID) AS absences

因为您看到的示例数据如下:

Employee ID person ID Meeting ID date
----------- --------- ---------- ----------
         23        25        123 2013-03-21
         24        25        456 2013-03-21
         25        25        789 2013-03-21

这3名不同的员工具有相同的人员ID


或者,或者您已经获得了正确的值;有10个不同的EmployeeID,但少于该PersonID


如果您仍要计算重复的人员ID,请更改

count(distinct personID) AS absences

count(personID) AS absences

答案 1 :(得分:0)

可以,只要每次会议至少有一个人参加即可。

WITH ALL_MEETING_EMPLOYEE_COMBOS AS
         ( SELECT EmployeeID, 
                  Meeting_ID,
                  date
             FROM (SELECT DISTINCT 
                          Employee_ID
                     FROM Attendance_Record
                  )
            CROSS JOIN 
                  ( SELECT DISTINCT 
                           meeting_id,
                           date
                      FROM attendance_record
                  )
   )
SELECT Employee_ID,
       Date,
       COUNT(1) AS MissedOnThisDayCount
  FROM ALL_MEETING_EMPLOYEE_COMBOS T1
 WHERE NOT EXISTS
         ( SELECT 1
             FROM ATTENDANCE_RECORD AR
            WHERE T1.employee_id = AR.employee_id
              AND T1.meeting_id = AR.meeting_id
         )

GROUP BY employee_id, date