Home  >  Q&A  >  body text

SQL question, query, procedure or function

This is the description.

There is a table that lists the time intervals required to perform a specific task:

id start Finish
1 07:00:00 11:00:00
2 12:30:00 17:00:00
3 11:30:00 14:00:00
4 09:30:00 11:30:00
5 10:00:00 15:00:00
6 09:00:00 13:30:00
7 07:00:00 11:30:00

These tasks cannot be completed at the same time. I need to find out the minimum number of days required to complete all tasks.

In this table, I can spend at least 5 days to complete the task.

day 1 => task 1 and task 2
day 2 => task 4 and task 3
day 3 => task 5
day 4 => task 6
day 5 => task 7

So the result should be 5. I hope it's clear, thank you in advance!

P粉253518620P粉253518620181 days ago264

reply all(1)I'll reply

  • P粉195200437

    P粉1952004372024-04-04 09:43:56

    SELECT COUNT(*)
    FROM test t1
    JOIN test t2 ON 
    -- these 2 conditions checks for overlapping
                    t1.start < t2.finish
                AND t2.start < t1.finish        
    -- this condition simply decreases the amount of combined rows
    -- to be examined, it does not effect the output
                AND t1.id <= t2.id                
    GROUP BY t1.id
    -- retrieve only maximal value
    ORDER BY 1 DESC LIMIT 1
    

    You must simply calculate the maximum number of simultaneous tasks. It is enough to check the start time of each task.

    https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=ee3034a307c32212db365ba06f654f9f

    reply
    0
  • Cancelreply