sql >> Database teknologi >  >> RDS >> Mysql

MySQL booking tilgængelighed, overlappende datointervaller

  1. Konstruer en liste over alle reservationsgrænser (dvs. start- og slutdatoer), der forekommer i den ønskede periode:

      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æg dertil den grænse, der optræder umiddelbart før den ønskede periode:

    -- [ 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. Lav en ydre joinforbindelse mellem dette resultat og bookings bord, holder alle grænserne, men inkluderer kun en reservation, hvis det bidrager til antallet af samtidige personer efter grænsen:

    FROM bookings RIGHT JOIN (
      -- [ from part 2 above ]
    ) t ON date_start <= boundary AND boundary < date_end
    
  4. Sum antallet af personer ved hver grænse:

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

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

At sætte det hele sammen:

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. pip install MySQL-python returnerer ude af stand til at finde vcvarsall.bat

  2. ORA-00936:manglende udtryksorakel

  3. 4 funktioner til at returnere året fra en dato i MariaDB

  4. Vælg Forespørgsel | Vælg Entires That Don't Start With a Number - MySQL