首頁  >  問答  >  主體

SQL問題、查詢、流程或函數

這是描述。

有一個表格,其中列出了執行特定任務所需的時間間隔:

id 開始 完成
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

這些任務無法同時完成。我需要找出完成所有任務最少需要多少天。

在這個表中,我至少可以花 5 天來完成任務。

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

所以結果應該是 5。我希望它很清楚,提前謝謝您!

P粉253518620P粉253518620180 天前255

全部回覆(1)我來回復

  • 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
    

    您必須簡單地計算同時任務的最大數量。檢查每個任務的開始時間就足夠了。

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

    回覆
    0
  • 取消回覆