我有一个重叠预订日期的临时表。这些日期可以以任何方式组合重叠,因为它们适用于多个可用房间。
我想创建一个返回一组合并日期的查询。 (结帐日期是可用日期。)
例如,以下数据
+--------+-------------+------------+------------+
| id | rental_unit | checkin | checkout |
+--------+-------------+------------+------------+
| 9144 | 224 | 2015-11-04 | 2015-12-27 |
| 352580 | 341 | 2015-12-01 | 2016-02-06 |
| 7519 | 224 | 2015-12-27 | 2016-01-05 |
| 9141 | 224 | 2016-01-05 | 2016-02-04 |
| 13834 | 341 | 2016-01-16 | 2016-01-23 |
| 9142 | 224 | 2016-02-05 | 2016-03-04 |
| 352581 | 341 | 2016-02-07 | 2016-03-12 |
| 11707 | 341 | 2016-02-22 | 2016-03-12 |
| 11239 | 224 | 2016-03-11 | 2016-03-19 |
| 11889 | 224 | 2016-03-20 | 2016-04-03 |
| 352582 | 341 | 2016-03-27 | 2016-04-07 |
+--------+-------------+------------+------------+
会回来:
+------------+------------+
| checkin | checkout |
+------------+------------+
| 2015-11-04 | 2016-03-19 |
| 2016-03-20 | 2016-04-07 |
+------------+------------+
谢谢!
答案 0 :(得分:1)
两个内部查询确定每组日期范围的签入和签出日期(上面的示例数据集中有2个)。我将这两组日期连接在一起,外部查询获得您想要的签入/结帐日期组合。
SELECT t2.checkin, MIN(t1.checkout) FROM
(
SELECT b1.checkout AS checkout
FROM bookings b1 INNER JOIN bookings b2 ON b1.checkout BETWEEN b2.checkin AND b2.checkout
GROUP BY b1.checkout
HAVING COUNT(*) = 1
) t1
INNER JOIN
(
SELECT b1.checkin AS checkin
FROM bookings b1 INNER JOIN bookings b2 ON b1.checkin BETWEEN b2.checkin AND b2.checkout
GROUP BY b1.checkout
HAVING COUNT(*) = 1
) t2
ON t2.checkin < t1.checkout
GROUP BY t2.checkin
点击以下链接查看正在运行的演示: