I need to calculate the business hours (8am - 5pm) between different dates. Here is the scenario:
Tickets get assigned to employees (Ticket_Submission
(DateTime)), then the employee creates a product (Build_Date
(Datetime)), now sometimes in order to create a product a medication needs to be built (Med_Date
(Datetime)). In order to calculate the how long it took for the employee to create a product,
I need to DATEDIFF
between Ticket_submission AND Build_Date
, however, if medication is involved, it had to be between Med_Date AND Build_Date
. It is OK to include weekends and holidays. The following helps me to get the difference in days:
.....
,IIF((med_date = buid_date OR ticket_submission = build_date), 1
, IIF(med_date IS NULL OR med_date < ticket_submission , (DATEDIFF(dd, ticket_submission,build_date))
, DATEDIFF(dd, med_date, build_date))) AS buildcompletedate,….
This only gives me the number of days, also, I know that if instead of DD, I put hours I can get the total number of hours between the 2 dates. But, how I can have these in business hours?
I do appreciate your help.
ticketID Ticket_submission Med_Date Build_Date
1549392 2017-04-07 10:31:06:210 2017-04-08 11:31:06:210 2017-04-09 12:30:08:110
1751406 2017-06-06 4:30:08:200 2018-08-06 3:30:08:200 2018-09-10 3:30:08:200
2583870 2019-11-20 1:20:01:100 NULL 2019-11-23 2:20:01:100
To help construct test sample, here is a common table expression that constructs the test sample in-memory:
; with Ticket (TicketID, Ticket_Submission, Med_Date, Build_Date)
AS
(
SELECT TicketID = 1549392, Ticket_Submission = CAST('2017-04-07 10:31:06:210' AS DATETIME2), Med_Date = CAST('2017-04-08 11:31:06:210' AS DATETIME2), Build_Date = CAST('2017-04-09 12:30:08:110' AS DATETIME2) UNION ALL
SELECT 1751406, CAST('2017-06-06 4:30:08:200' AS DATETIME2), CAST('2018-08-06 3:30:08:200' AS DATETIME2), CAST('2018-09-10 3:30:08:200 ' AS DATETIME2) UNION ALL
SELECT 2583870, CAST('2019-11-20 1:20:01:100' AS DATETIME2), CAST(NULL AS DATETIME2), CAST('2019-11-23 2:20:01:100' AS DATETIME2)
)
select
TicketID,
0 AS RoundedBusinessHoursBetweenDates /* Update with answer code */
from Ticket
Expected Results
TicketID RoundedBusinessHoursBetweenDates
-------- --------------------------------
1549392 10
1751406 307
2583870 20????
Rounding
- It's OK to round hours
- for example, instead of 4 hours 30 min, have it as 5 hours.
Understanding the Calculation, Step-By-Step
- For the first row (TicketID 1549392), I expect to see:
- 10 hours ( about 5 hours and 30 min from 11:31 am till 5 pm (for the first day)+ 4.5 hours for 8 am till 12:30 for the second day)
- For the second row (TicketID 1751406), I expect to see:
- 2 hours for the first day (for the med_build date) + 8 hours for the last day (8 am till 3:30 pm) + 9 * remaining days between these 2 days
- For the third row (TicketID 2583870), if
Med_Date
isNULL
then only the difference from ticket_submission till build_date