SQL Server 2005 及更高版本
假设:
- 任务开始日期和结束日期值始终相同。
- 周开始和结束日期是根据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