Traffic Light System Analytics

Start Timer

0:00:00

Upvote
0
Downvote
Save question
Mark as completed
View comments (2)

You’re a data engineer working for a smart city traffic management system. The city has installed IoT-connected traffic lights at multiple intersections to monitor traffic congestion and optimize light timing dynamically.

Write a SQL query to calculate the average duration (in seconds) that each intersection’s traffic lights stay red across all recorded days.

Note: A red interval for a given signal is defined as the time between when that signal’s light changes to 'Red' and the next time it changes to 'Green' for the same signal_id.

Note: Return intersection_id and avg_red_duration_seconds (rounded to 2 decimal places). Sort results in ascending order by intersection_id.

Assumptions:

  • The light cycle always follows: Green → Yellow → Red → Green
  • The dataset spans multiple days
  • There are no missing transitions (e.g., every Red has a following Green event for that signal_id)

Schema

Input:

traffic_signals table

Column Type
event_id INTEGER (PRIMARY KEY)
signal_id INTEGER
intersection_id INTEGER
light_color VARCHAR
changed_at DATETIME

Output:

Column Type
intersection_id INTEGER
avg_red_duration_seconds FLOAT

Example

Input:

traffic_signals table

event_id signal_id intersection_id light_color changed_at
1 101 1 Green 2025-11-15 08:00:00
2 101 1 Yellow 2025-11-15 08:01:00
3 101 1 Red 2025-11-15 08:02:00
4 101 1 Green 2025-11-15 08:03:30
5 102 2 Green 2025-11-15 08:00:00
6 102 2 Yellow 2025-11-15 08:01:30
7 102 2 Red 2025-11-15 08:03:00
8 102 2 Green 2025-11-15 08:04:00

Output:

intersection_id avg_red_duration_seconds
1 90.00
2 60.00
.
.
.
.
.


Comments

Loading comments