my sql server table named timesheet has 4 columns
employee_id int
task_start_date datetime
task_end_date datetime
hours_worked int
I need to derive week start date and week end date and total hours the employee has worked in that week. My resulting dataset should have 4 columns –
Week_Start_Date Week_End_Date Employee_Id Total_Hours_Charged
In other words, i need to get total hours charged by each employee for all the weeks from that table. Could anyone please help me write a query for that?
SQL Server 2005 and above
Assumptions:
You can use the
DATEPARTfunction to find the day of the week for a given date and then useDATEADDfunction to provide the output fromDATEPARTas input to calculate the first and last days of the week.Click here to view the demo in SQL Fiddle.
Script:
The script calculates the week totals hours assuming that week begins on Sunday and ends on Saturday.
Output: