如何根据表格中的日期列按周开始和结束日期计算总计?

时间:2012-05-04 19:48:25

标签: sql-server

我的sql server表名为timesheet有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

换句话说,我需要从该表中获得每位员工在整个星期内收取的总时数。有人可以帮我写一个查询吗?

1 个答案:

答案 0 :(得分:1)

SQL Server 2005及更高版本

假设:

  1. 任务开始日期和结束日期值始终相同
  2. 周开始日期和结束日期根据 task_start_date 计算。
  3. 您可以使用DATEPART函数查找给定日期的星期几,然后使用DATEADD函数提供DATEPART的输出作为输入来计算第一个和一周的最后几天。

    Click here to view the demo in 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