简体   繁体   中英

Get nearest continuous date period MySQL

I have this MySQL table:

| Date           | Room | State |
|2015-06-15      | 26   | 1     | 
|2015-06-16      | 26   | 1     | 
|2015-06-17      | 26   | 1     | 
|2015-06-18      | 26   | 1     | 
|2015-06-20      | 26   | 1     | 
|2015-06-21      | 26   | 0     | 
|2015-06-22      | 26   | 0     | 
|2015-06-23      | 26   | 1     | 
|2015-06-24      | 26   | 0     | 
|2015-06-30      | 26   | 1     | 
|2015-07-01      | 26   | 1     |

I want to get the first date of the beginning of useful nearest (it means continuous day, State = 1 ) booking period (for example, 2 days).

How can I do it?

SELECT d.*
FROM   dates d
WHERE  EXISTS(SELECT `Date`
              FROM   dates
              WHERE  `Room` = d.`Room`
                     AND `Date` = Date_add(d.`Date`, INTERVAL 1 DAY)
                     AND `State` = 1)
       AND d.`State` = 1;

for 2 Days.

SET @days=3;

SELECT d.*
FROM   dates d
WHERE  (SELECT Count(`date`)
        FROM   dates
        WHERE  `Room` = d.`Room`
               AND `Date` <= Date_add(d.`Date`, INTERVAL @days - 1 DAY)
               AND `Date` >= d.`Date`
               AND `State` = 1) >= @days
       AND d.`State` = 1; 

for dynamic days value. And the testdata I used:

create table Dates(
`Date` DATE,
`Room` INT DEFAULT 26,
`State` BOOL DEFAULT 0);

INSERT INTO  Dates (`Date`,`State`) VALUES
('2015-01-01',1),
('2015-01-02',0),
('2015-01-03',1),
('2015-01-04',1),
('2015-01-05',0),
('2015-01-06',1),
('2015-01-07',1),
('2015-01-08',1),
('2015-01-09',0),
('2015-01-10',1),
('2015-01-11',1),
('2015-01-12',1),
('2015-01-13',1);

The query returns actually all posible dates. To get only one date add a LIMIT 1 at the end of the statement. But maybe it can be help full to get later Startdays that are Possible. The second query returns with the testdata the following Dates:

2015-01-06  26  1
2015-01-10  26  1
2015-01-11  26  1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM