Skip to content
Advertisement

How do I calculate amount of time in each week between two dates – SQL Server

[EDITED TO SIMPLIFY]

I have 500+ records. All of which have a reference number, a start date, an end date and a total machining time.

Starting at the start date, I need to calculate how many machining hours fall into 1 week and how many fall into the next. Our working days are Monday to Thursday 8 Hours & Friday 4 Hours.

Ref 321 has a start of 25/2 which is a Tuesday and a finish date of 27/2 which is a Thursday in the same week. This will calculate as all 18 hours being in the same week. Ref 123 has a start of 24/01. This is a Friday in Week 4 of 2020. Based on my rules, that would be 4 hours in week 4 and 24 Hours in week 5.

I have a table called ‘DatesList’ which has all days on it (as well as week number and working hours).

I need my table to list each record for each week and I’ll do the grouping on a separate report.

In effect I’d like

Advertisement

Answer

You can start with creating some reference tables.

For the example those are just temporary tables.

Reference data:

Some sample data:

Then you can run a query that uses the reference tables.

Returns:

A test on db<>fiddle here

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement