如何使用SQL创建查询以使每一行连续一天可用。例如,我想连续3天找到至少3个可用房间
原始表
Date Available rooms
---- ---------------
01/12/16 4
02/12/16 5
03/12/16 5
04/12/16 5
05/12/16 4
06/12/16 0
07/12/16 3
08/12/16 4
09/12/16 4
结果低于
Date EndDate
-------- --------
01/12/16 03/12/16
02/12/16 04/12/16
03/12/16 05/12/16
07/12/16 09/12/16
答案 0 :(得分:3)
尝试使用LEAD()函数,如下面的查询
SELECT d as StartDate, EndDate
FROM
(SELECT d,
CASE
WHEN available_rooms > 2
AND LEAD(available_rooms,1) OVER(order by d) > 2
AND LEAD(available_rooms,2) OVER(order by d) > 2
THEN LEAD(d,2) OVER(order by d)
END EndDate
FROM table1 t) t1
WHERE EndDate is not null;
以下是我收到的输出
答案 1 :(得分:2)
<强> SQL DEMO 强>
SELECT T1.[Date], T3.[Date]
FROM Table1 T1
JOIN Table1 T2
ON T1.[Date] = DATEADD(day, -1, T2.[Date])
JOIN Table1 T3
ON T1.[Date] = DATEADD(day, -2, T3.[Date])
WHERE T1.[Available rooms] >= 3
AND T2.[Available rooms] >= 3
AND T3.[Available rooms] >= 3
<强>输出强>