1

我的名为 timesheet 的 sql server 表有 4 列

employee_id int
task_start_date datetime
task_end_date datetime
hours_worked int

我需要得出周开始日期和周结束日期以及员工在该周工作的总小时数。我生成的数据集应该有 4 列 - Week_Start_Date Week_End_Date Employee_Id Total_Hours_Charged

换句话说,我需要从该表中获取每个员工在所有周内收取的总小时数。谁能帮我写一个查询?

4

1 回答 1

1

SQL Server 2005 及更高版本

假设:

  1. 任务开始日期和结束日期值始终相同
  2. 周开始和结束日期是根据task_start_date计算的。

您可以使用该DATEPART函数查找给定日期的星期几,然后使用DATEADD函数提供输出DATEPART作为输入来计算一周的第一天和最后一天。

单击此处查看 SQL Fiddle 中的演示。

脚本:

假设该周从星期日开始并在星期六结束,该脚本计算该周的总小时数。

CREATE TABLE timesheet
(
        employee_id     int
  ,     task_start_date datetime
  ,     task_end_date   datetime
  ,     hours_worked    int
);

INSERT INTO timesheet
    (employee_id, task_start_date, task_end_date, hours_worked) 
    VALUES
      (1, '20120331', '20120331', 6),
      (1, '20120401', '20120401', 3),
      (1, '20120403', '20120403', 8),
      (1, '20120409', '20120409', 5),
      (1, '20120412', '20120412', 4),
      (2, '20120402', '20120402', 7),
      (2, '20120403', '20120403', 6),
      (3, '20120409', '20120409', 4),
      (1, '20120412', '20120412', 8);

;WITH empworkhours AS
(
    SELECT  DATEADD(DAY
                ,   -(DATEPART(dw, task_start_date) -1)
                ,   task_start_date) AS week_start
        ,   DATEADD(DAY
                ,   7 - (DATEPART(dw, task_start_date))
                ,   task_start_date) AS week_end
        ,   employee_id
        ,   hours_worked
    FROM    timesheet
)
SELECT      week_start
        ,   week_end
        ,   employee_id
        ,   SUM(hours_worked) total_hrs_per_week
FROM        empworkhours
GROUP BY    week_start
        ,   week_end
        ,   employee_id;

输出:

WEEK_START      WEEK_END        EMPLOYEE_ID TOTAL_HRS_PER_WEEK
--------------  --------------  ----------- -----------------
March, 25 2012  March, 31 2012       1               6
April, 01 2012  April, 07 2012       1              11
April, 01 2012  April, 07 2012       2              13
April, 08 2012  April, 14 2012       1              17
April, 08 2012  April, 14 2012       3               4
于 2012-05-04T20:05:23.477 回答