查询同时计算日期和总和数

时间:2014-02-05 15:58:45

标签: sql ms-access ms-access-2003

我在Access 2003中有以下数据:

Emp_ID  Name          WorkDays   TotalOT
------  ------------  ---------  -------
6       Dobles        1/25/2014  0
6       Dobles        1/27/2014  1.5
6       Dobles        1/28/2014  5
6       Dobles        1/29/2014  0
6       Dobles        1/30/2014  1
7       Alfaro        1/25/2014  4
7       Alfaro        1/27/2014  3.5
7       Alfaro        1/28/2014  0
7       Alfaro        1/29/2014  1
7       Alfaro        1/30/2014  5
7       Alfaro        1/31/2014  0

我正在尝试使用如下结果构建查询:

Emp_ID  Name          WorkDays   TotalOT
------  ------------  ---------  -------
6       Dobles        5          7.6
7       Alfaro        6          13.5

到目前为止,这是我的代码:

SELECT DISTINCTROW 
    (Employee_Tbl.EmployeeID) AS Emp_ID, 
    (Employee_Tbl.FullName) AS Name, 
    Sum(Attendance_Tbl.WorkDate) AS TotalWorkDays, 
    Sum(Attendance_Tbl.TotalOTHrs) AS TotalOT
FROM 
    Attendance_Tbl 
    INNER JOIN 
    Employee_Tbl 
        ON Attendance_Tbl.EmployeeID = Employee_Tbl.EmployeeID
WHERE (((Attendance_Tbl.WorkDate)>=#1/25/2014# 
    And (Attendance_Tbl.WorkDate)<=#1/31/2014#))
GROUP BY 
    Employee_Tbl.EmployeeID, 
    Employee_Tbl.FullName, 
    Attendance_Tbl.WorkDate, 
    Attendance_Tbl.TotalOTHrs;

但是这给了我

Emp_ID  Name    TotalWorkDays  TotalOT
------  ------  -------------  -------
     6  Dobles          41664        0
     6  Dobles          41666      1.5
     6  Dobles          41667        5
     6  Dobles          41668        0
     6  Dobles          41669        1
     7  Alfaro          41664        4
     7  Alfaro          41666      3.5
     7  Alfaro          41667        0
     7  Alfaro          41668        1
     7  Alfaro          41669        5
     7  Alfaro          41670        0

我做错了什么?

1 个答案:

答案 0 :(得分:2)

你需要做三件事:

  1. 删除DISTINCTROW关键字。
  2. 将日期的Sum()功能更改为Count()
  3. 从GROUP BY子句中删除日期和OT字段。您只需要GROUP by EmployeeID和name。
  4. 生成的查询将是

    SELECT 
        Employee_Tbl.EmployeeID AS Emp_ID, 
        Employee_Tbl.FullName AS Name, 
        Count(Attendance_Tbl.WorkDate) AS TotalWorkDays, 
        Sum(Attendance_Tbl.TotalOTHrs) AS TotalOT
    FROM 
        Attendance_Tbl 
        INNER JOIN 
        Employee_Tbl 
            ON Attendance_Tbl.EmployeeID = Employee_Tbl.EmployeeID
    WHERE (((Attendance_Tbl.WorkDate)>=#1/25/2014# 
        And (Attendance_Tbl.WorkDate)<=#1/31/2014#))
    GROUP BY Employee_Tbl.EmployeeID, Employee_Tbl.FullName;
    

    返回

    Emp_ID  Name    TotalWorkDays  TotalOT
    ------  ------  -------------  -------
         6  Dobles              5      7.5
         7  Alfaro              6     13.5