2

我有一个可用日期块表(在我的情况下为 7 天),它可能是连续的,也可能不是连续的:

start_date    end_date    booked    id    room_id

2012-07-14    2012-07-21    0       1        6
2012-07-21    2012-07-28    0       2        6
2012-07-28    2012-08-04    1       3        6
2012-08-04    2012-08-11    0       4        6

我想做的是能够得到一个结果集,在一个日期范围内,每 X 周连续未预订的日期给我一行。

因此,对于从 7 月 14 日开始并使用上表数据的 2 周区块,我预计会出现以下情况:

start_date    end_date    booked
2012-07-14    2012-07-28    0

由于预订了其中一个组成周,因此不会退回第二个 2 周。

以下是我已经尝试过的一些想法:

SELECT 
    MIN(start_date) AS start_date_min,
    MAX(end_date) AS end_date_max,
    CAST(GROUP_CONCAT(id) AS CHAR) AS ids,
    SUM(booked) AS booked
FROM 
    available_dates
WHERE
    (start_date>=20120714 AND end_date<=DATE_ADD(20120714, INTERVAL 14 DAY))
GROUP BY
    room_id
HAVING
    end_date_max=DATE_ADD(20120714, INTERVAL 14 DAY)

这让我成为了一部分,但并没有让我获得连续的结果——这是重要的部分。当我扩大测试数据时,它也只返回一个结果(可能是因为 HAVING 子句)。

谁能指出我正确的方向?

4

1 回答 1

1

如果您有日历或 numbers表格:

CREATE TABLE num
( i INT NOT NULL
, PRIMARY KEY (i)
) ;

INSERT INTO num 
  (i) 
VALUES
  (0), (1), (2), ..., (1000) ;

你可以使用这样的东西:

SELECT 
    avail.room_id,
    MIN(avail.start_date) AS start_date_min,
    MAX(avail.end_date) AS end_date_max,
    CAST(GROUP_CONCAT(avail.id) AS CHAR) AS ids,
    SUM(avail.booked) AS booked
FROM 
    available_dates AS avail
  CROSS JOIN
    ( SELECT DATE('2012-07-14') AS start_date_check
           , 52                 AS max_week_check
    ) AS param
  JOIN
    num
      ON  avail.start_date = param.start_date_check + INTERVAL num.i WEEK
      AND num.i < param.max_week_check
WHERE
    avail.booked = 0
GROUP BY
    avail.room_id,
    ( num.i / 2 )        
HAVING
    COUNT(*) = 2

你也可以这样:

WHERE
    1 =1                         --- no WHERE condition
GROUP BY
    avail.room_id,
    ( num.i / 2 )        
HAVING                           --- and optionally
    SUM(avail.booked) = 0        --- this
于 2012-07-10T15:07:53.090 回答