Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

mysql - SQL get consecutive starting and end date with specific period

I have a hotel_availablities table something like this.

date availability
2021-01-15 y
2021-01-16 y
2021-01-17 y
2021-01-18 n
2021-01-19 n
2021-01-20 y
2021-01-21 n
2021-01-22 y
2021-01-23 y
question from:https://stackoverflow.com/questions/66058598/sql-get-consecutive-starting-and-end-date-with-specific-period

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a gaps and islands problem. Assuming you are using MySQL 8+, we can use the difference in row numbers method here:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (ORDER BY date) rn1,
              ROW_NUMBER() OVER (PARTITION BY availability ORDER BY date) rn2
    FROM yourTable
)

SELECT MIN(date) AS start_date, MAX(date) AS end_date, COUNT(*) AS cnt
FROM cte
WHERE availability = 'y'
GROUP BY rn1 - rn2
HAVING COUNT(*) >= 2;    -- but change to COUNT(*) >= 3, e.g. for three days in a row

screen capture from demo link below

Demo

Note that my query does not give the exact output you expect, but maybe this would be enough for your requirement. If you wanted to break out each island larger than 2 days in terms of pairs of 2 days at a time, you might have to also bring in a calendar table here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[6] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

57.0k users

...