sql >> Databasteknik >  >> RDS >> Mysql

MySQL-bokningstillgänglighet, överlappande datumintervall

  1. Skapa en lista över alla bokningsgränser (d.v.s. start- och slutdatum) som inträffar under den önskade perioden:

      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
    
  2. Lägg därtill gränsen som inträffar omedelbart före den önskade perioden:

    -- [ 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
    
  3. Gör en yttre sammanfogning mellan detta resultat och bookings tabell, håller alla gränser men inkluderar bara en bokning om det bidrar till antalet samtidiga personer efter gränsen:

    FROM bookings RIGHT JOIN (
      -- [ from part 2 above ]
    ) t ON date_start <= boundary AND boundary < date_end
    
  4. Summa antalet personer vid varje gräns:

    SELECT IFNULL(SUM(quantity),0) AS simultaneous_people
    -- [ from part 3 above ]
    GROUP BY boundary
    
  5. Hitta max och minimum:

    SELECT MIN(simultaneous_people),
           MAX(simultaneous_people)
    FROM (
      -- [ from part 4 above ]
    ) t
    

Att lägga ihop allt:

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

Se den på sqlfiddle .



  1. SQL Konsekutiva poster med antal

  2. Slå samman och uppdatera primärnyckeln

  3. Hur man sammanfogar strängar i SQL Server med CONCAT()

  4. Förfina sökresultaten baserat på filtren