|
| 1 | +/* |
| 2 | +Human Traffic of Stadium |
| 3 | +https://leetcode.com/problems/human-traffic-of-stadium/ |
| 4 | +
|
| 5 | +Table: Stadium |
| 6 | +
|
| 7 | ++---------------+---------+ |
| 8 | +| Column Name | Type | |
| 9 | ++---------------+---------+ |
| 10 | +| id | int | |
| 11 | +| visit_date | date | |
| 12 | +| people | int | |
| 13 | ++---------------+---------+ |
| 14 | +visit_date is the primary key for this table. |
| 15 | +Each row of this table contains the visit date and visit id to the stadium with the number of people during the visit. |
| 16 | +No two rows will have the same visit_date, and as the id increases, the dates increase as well. |
| 17 | +
|
| 18 | +Write an SQL query to display the records with three or more rows with consecutive id's, and the number of people is greater than or equal to 100 for each. |
| 19 | +
|
| 20 | +Return the result table ordered by visit_date in ascending order. |
| 21 | +
|
| 22 | +The query result format is in the following example. |
| 23 | +
|
| 24 | +Stadium table: |
| 25 | ++------+------------+-----------+ |
| 26 | +| id | visit_date | people | |
| 27 | ++------+------------+-----------+ |
| 28 | +| 1 | 2017-01-01 | 10 | |
| 29 | +| 2 | 2017-01-02 | 109 | |
| 30 | +| 3 | 2017-01-03 | 150 | |
| 31 | +| 4 | 2017-01-04 | 99 | |
| 32 | +| 5 | 2017-01-05 | 145 | |
| 33 | +| 6 | 2017-01-06 | 1455 | |
| 34 | +| 7 | 2017-01-07 | 199 | |
| 35 | +| 8 | 2017-01-09 | 188 | |
| 36 | ++------+------------+-----------+ |
| 37 | +
|
| 38 | +Result table: |
| 39 | ++------+------------+-----------+ |
| 40 | +| id | visit_date | people | |
| 41 | ++------+------------+-----------+ |
| 42 | +| 5 | 2017-01-05 | 145 | |
| 43 | +| 6 | 2017-01-06 | 1455 | |
| 44 | +| 7 | 2017-01-07 | 199 | |
| 45 | +| 8 | 2017-01-09 | 188 | |
| 46 | ++------+------------+-----------+ |
| 47 | +The four rows with ids 5, 6, 7, and 8 have consecutive ids and each of them has >= 100 people attended. Note that row 8 was included even though the visit_date was not the next day after row 7. |
| 48 | +The rows with ids 2 and 3 are not included because we need at least three consecutive ids. |
| 49 | +*/ |
| 50 | + |
| 51 | +SELECT DISTINCT(s1.id) as id, s1.visit_date, s1.people |
| 52 | +FROM Stadium AS s1, Stadium AS s2, Stadium AS s3 |
| 53 | +WHERE |
| 54 | + (s1.people >= 100 AND s2.people >= 100 AND s3.people >= 100 AND s1.id = s2.id - 1 AND s2.id = s3.id - 1 AND s1.id = s3.id - 2) OR -- S1, S2, S3 |
| 55 | + (s1.people >= 100 AND s2.people >= 100 AND s3.people >= 100 AND s1.id = s2.id + 1 AND s2.id = s3.id - 2 AND s1.id = s3.id - 1) OR -- S2. S1. S3 |
| 56 | + (s1.people >= 100 AND s2.people >= 100 AND s3.people >= 100 AND s1.id = s2.id + 2 AND s2.id = s3.id - 1 AND s1.id = s3.id + 1) -- S2 S3 S1 |
| 57 | +ORDER BY s1.id ASC |
0 commit comments