1

我有一张预订表:

  • 标识(整数)
  • 数量 (tinyint)
  • date_start(时间戳)
  • date_end(时间戳)

预订可以重叠,因此例如可以同时有 20 个预订。现在我想做两个查询:

1) 检索给定时间段内的最大数量总和。

2) 检索给定时间段内的最小数量总和。

我不知道如何将重叠预订的数量加在一起,而不是非重叠预订的数量。任何帮助将不胜感激。

编辑:为了清楚起见,我画了一张图片:http: //i.imgur.com/8GDLV.png

4

2 回答 2

2
  1. 构建在所需时间段内出现的所有预订边界(即开始和结束日期)的列表:

      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. 添加到紧接在所需时间段之前出现的边界:

    -- [ 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. 在此结果和表之间进行外部连接,保留所有边界,但仅包括一个预订,如果它有助于在边界之后bookings的同时人数:

    FROM bookings RIGHT JOIN (
      -- [ from part 2 above ]
    ) t ON date_start <= boundary AND boundary < date_end
    
  4. 将每个边界的人数相加:

    SELECT IFNULL(SUM(quantity),0) AS simultaneous_people
    -- [ from part 3 above ]
    GROUP BY boundary
    
  5. 求最大值和最小值:

    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上查看。

于 2012-08-31T11:16:42.647 回答
1

问题中的给定数据结构中没有用于分组的字段。因此,假设您按ID.

1)。为了得到最大的利用MAX

SELECT MAX(TotalQty) FROM
(
    SELECT SUM(Quantity) AS TotalQty FROM Bookings
    WHERE date_End<='<To Date>'
    AND date_Start>='<From Date>'
    GROUP BY id
) SumQty

2)。获得最大最小值MIN

SELECT MIN(TotalQty) FROM
(
    SELECT SUM(Quantity) AS TotalQty FROM Bookings
    WHERE date_End<='<To Date>'
    AND date_Start>='<From Date>'
    GROUP BY id
) SumQty

看到这个 SQLFiddle

于 2012-08-31T10:43:09.540 回答