Human Traffic of Stadium

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.
Return the result table ordered by visit_date in ascending order.
Example:

Table: Stadium 
+------+------------+-----------+
| id   | visit_date | people    |
+------+------------+-----------+
1    | 2017-01-01 | 10        |
2    | 2017-01-02 | 109       |
3    | 2017-01-03 | 150       |
4    | 2017-01-04 | 99        |
5    | 2017-01-05 | 145       |
6    | 2017-01-06 | 1455      |
7    | 2017-01-07 | 199       |
8    | 2017-01-09 | 188       |
+------+------------+-----------+

Output:
+------+------------+-----------+
| id   | visit_date | people    |
+------+------------+-----------+
5    | 2017-01-05 | 145       |
6    | 2017-01-06 | 1455      |
7    | 2017-01-07 | 199       |
8    | 2017-01-09 | 188       |
+------+------------+-----------+    

Approach

Mysql


SELECT DISTINCT D1.* 
FROM
STADIUM D1, STADIUM D2, STADIUM D3
WHERE
D1.PEOPLE >= 100 AND D2.PEOPLE >= 100 
AND D3.PEOPLE >= 100 AND
((D1.ID + 1 =  D2.ID AND D1.ID + 2 = D3.ID) OR
(D1.ID - 1 = D2.ID AND D1.ID + 1 = D3.ID) OR
(D1.ID - 2 = D2.ID AND D1.ID - 1 = D3.ID)) 
ORDER BY D1.ID;


No comments:

Post a Comment