-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConsecutive Available Seats
52 lines (44 loc) · 1.09 KB
/
Consecutive Available Seats
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
Several friends at a cinema ticket office would like to reserve consecutive available seats.
Can you help to query all the consecutive available seats order by the seat_id using the following cinema table?
Cinema table:
+---------+------+
| seat_id | free |
+---------+------+
| 1 | 1 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
+---------+------+
Result table:
+---------+
| seat_id |
+---------+
| 3 |
| 4 |
| 5 |
+---------+
Note:
The seat_id is an auto increment int, and free is bool ('1' means free, and '0' means occupied.).
Consecutive available seats are more than 2(inclusive) seats consecutively available.
Answer:
-- #1
SELECT T.SEAT_ID
FROM (
SELECT SEAT_ID,
LAG(FREE) OVER(ORDER BY SEAT_ID) AS PREV_FREE,
FREE,
LEAD(FREE) OVER(ORDER BY SEAT_ID) AS NEXT_FREE
FROM CINEMA
) T
WHERE (T.PREV_FREE = 1 AND T.FREE = 1)
OR (T.FREE = 1 AND T.NEXT_FREE = 1)
;
-- #2
SELECT DISTINCT B.SEAT_ID
FROM CINEMA A
CROSS JOIN CINEMA B
WHERE ABS(A.SEAT_ID - B.SEAT_ID) = 1
AND A.FREE = 1
AND B.FREE = 1
;