Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <h1>SQL Server 2005 and above</h1> <h3>Assumptions:</h3> <ol> <li>Task start and end date values are always <strong>same</strong>.</li> <li>Week start and end dates are calculated based on the <strong>task_start_date</strong>.</li> </ol> <p>You can use the <code>DATEPART</code> function to find the day of the week for a given date and then use <code>DATEADD</code> function to provide the output from <code>DATEPART</code> as input to calculate the first and last days of the week.</p> <p><a href="http://sqlfiddle.com/#!6/2ff4f/1" rel="nofollow"><strong>Click here to view the demo in SQL Fiddle.</strong></a></p> <h3>Script:</h3> <p>The script calculates the week totals hours assuming that week begins on <em>Sunday</em> and ends on <em>Saturday</em>. </p> <pre><code>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; </code></pre> <h3>Output:</h3> <pre><code>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 </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload