-
希望する期間に発生するすべての予約境界(つまり、開始日と終了日)のリストを作成します。
SELECT date_start AS boundary FROM bookings WHERE date_start BETWEEN @start AND @end UNION SELECT date_end FROM bookings WHERE date_end BETWEEN @start AND @end
-
それに加えて、希望する期間の直前に発生する境界:
-- [ from part 1 above ] UNION SELECT MAX(boundary) FROM ( SELECT MAX(date_start) AS boundary FROM bookings WHERE date_start <= @start UNION ALL SELECT MAX(date_end) FROM bookings WHERE date_end <= @end ) t
-
この結果と
bookings
を外部結合します テーブル、すべての境界を保持しますが、後の同時人数に寄与する場合にのみ予約を含めます 境界:FROM bookings RIGHT JOIN ( -- [ from part 2 above ] ) t ON date_start <= boundary AND boundary < date_end
-
各境界の人数を合計します:
SELECT IFNULL(SUM(quantity),0) AS simultaneous_people -- [ from part 3 above ] GROUP BY boundary
-
最大値と最小値を見つける:
SELECT MIN(simultaneous_people), MAX(simultaneous_people) FROM ( -- [ from part 4 above ] ) t
すべてをまとめる:
SELECT MIN(simultaneous_people),
MAX(simultaneous_people)
FROM (
SELECT IFNULL(SUM(quantity),0) AS simultaneous_people
FROM bookings RIGHT JOIN (
SELECT date_start AS boundary
FROM bookings
WHERE date_start BETWEEN @start AND @end
UNION
SELECT date_end
FROM bookings
WHERE date_end BETWEEN @start AND @end
UNION
SELECT MAX(boundary)
FROM (
SELECT MAX(date_start) AS boundary
FROM bookings
WHERE date_start <= @start
UNION ALL
SELECT MAX(date_end)
FROM bookings
WHERE date_end <= @end
) t
) t ON date_start <= boundary AND boundary < date_end
GROUP BY boundary
) t
sqlfiddle でご覧ください 。