Approach
Relational aggregation
For Employee Task Duration and Concurrent Tasks, the query transforms and combines relational rows, then filters or aggregates them into the requested result.
- Identify the source rows and join keys.
- Apply filters before aggregation when possible.
- Group, rank, or project the final columns required by the result.
Code notes
- 39 lines of SQL from the credited upstream file 3156.sql.
- The implementation keeps its working state in language-native values and containers.
- No explicit loop blocks detected.
Complexity
Review join cardinality, grouping keys, and available indexes when estimating query cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1WITH2 EmployeeTimes AS (3 SELECT DISTINCT employee_id, start_time AS `time`4 FROM Tasks5 UNION DISTINCT6 SELECT DISTINCT employee_id, end_time AS `time`7 FROM Tasks8 ),9 Segments AS (10 SELECT11 employee_id,12 `time` AS start_time,13 LEAD(`time`) OVER(PARTITION BY employee_id ORDER BY `time`) AS end_time14 FROM EmployeeTimes15 ),16 SegmentsCount AS (17 SELECT18 Segments.*,19 COUNT(*) AS concurrent_count20 FROM Segments21 INNER JOIN Tasks22 USING (employee_id)23 WHERE24 Segments.start_time >= Tasks.start_time25 AND Segments.end_time <= Tasks.end_time26 GROUP BY 1, 2, 327 )28SELECT29 employee_id,30 FLOOR(31 SUM(32 TIME_TO_SEC(TIMEDIFF(end_time, start_time)) / 360033 )34 ) AS total_task_hours,35 MAX(concurrent_count) AS max_concurrent_tasks36FROM SegmentsCount37GROUP BY 138ORDER BY 1;39