mysql按连续日期选择行

时间:2012-07-10 14:35:39

标签: mysql date

我有一个可用日期块表(在我的情况下为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子句)。

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分: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