重叠预订的最小和最大数量

时间:2016-01-14 04:26:18

标签: mysql date

我的预订系统有多个同时预订,每个预订都有一个计数。我需要获得指定日期范围的最小值和最大值(在这种情况下为一天)。我找到了一些好的代码here,它在测试中非常有用。但在我的实现中,它在这个特定的实例中失败了:

  • 它不会计算在查询范围之前开始并在查询范围内结束的预订。

我该如何解决这个问题?

以下是一个例子:

此预订包含以下属性: 列表(多个预订可以拥有的ID,但在这种情况下只有一个):2f23f23f

date_start:2016-01-15 08:00:00

date_end:2016-01-17 08:00:00

陈述:活跃

数:1

结果:

min_count:0

max_count:0

它应该返回:

min_count:0

max_count:1

如果我们查询的相同,但日期范围为2016-01-16 00:00:00 - 2016-01-16 23:59:59,则会返回正确答案:

min_count:1

max_count:1

这是MYSQL:

SELECT
    MAX(simultaneous) AS max_count,
    MIN(simultaneous) AS min_count
FROM (
  SELECT IFNULL(SUM(
      (
          CASE WHEN (
                listings = '2f23f23f'
                AND 
                    (state = 'active')
          )
          THEN count
          ELSE 0
          END
      )
    ),0) AS simultaneous
  FROM   bookings RIGHT JOIN (
    SELECT date_start AS boundary
    FROM   bookings
    WHERE date_start BETWEEN '2016-01-17 00:00:00' AND '2016-01-17 23:59:59'

  UNION
    SELECT date_end
    FROM   bookings
    WHERE  date_end BETWEEN '2016-01-17 00:00:00' AND '2016-01-17 23:59:59'

  UNION
    SELECT MAX(boundary)
    FROM (
      SELECT MAX(date_start) AS boundary
      FROM   bookings
      WHERE date_start <= '2016-01-17 00:00:00'

    UNION ALL
      SELECT MAX(date_end)
      FROM   bookings
      WHERE date_end <= '2016-01-17 23:59:59'

    ) t
  ) t ON date_start <= boundary AND boundary < date_end
  LEFT OUTER JOIN cart ON cart_bookings = id
  GROUP BY boundary
) t

1 个答案:

答案 0 :(得分:0)

哇,好的,这就是答案。原来显然没有完成。它需要包括所请求时间范围的开始/结束日期。

  UNION
    SELECT :date_start
  UNION
    SELECT :date_end

完整代码:

SELECT
    MAX(simultaneous) AS max_count,
    MIN(simultaneous) AS min_count
FROM (
  SELECT IFNULL(SUM(
      (
          CASE WHEN (
                listings = '2f23f23f'
                AND 
                    (state = 'active')
          )
          THEN count
          ELSE 0
          END
      )
    ),0) AS simultaneous
  FROM   bookings RIGHT JOIN (
    SELECT date_start AS boundary
    FROM   bookings
    WHERE date_start BETWEEN '2016-01-17 00:00:00' AND '2016-01-17 23:59:59'

  UNION
    SELECT date_end
    FROM   bookings
    WHERE  date_end BETWEEN '2016-01-17 00:00:00' AND '2016-01-17 23:59:59'

  UNION
    SELECT MAX(boundary)
    FROM (
      SELECT MAX(date_start) AS boundary
      FROM   bookings
      WHERE date_start <= '2016-01-17 00:00:00'

    UNION ALL
      SELECT MAX(date_end)
      FROM   bookings
      WHERE date_end <= '2016-01-17 23:59:59'

    ) t
  UNION
    SELECT :date_start
  UNION
    SELECT :date_end
  ) t ON date_start <= boundary AND boundary < date_end
  LEFT OUTER JOIN cart ON cart_bookings = id
  GROUP BY boundary
) t