我的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
换句话说,我需要从该表中获得每位员工在整个星期内收取的总时数。有人可以帮我写一个查询吗?
答案 0 :(得分:1)
您可以使用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