Approach
Relational aggregation
For Find Overlapping Shifts II, 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
- 41 lines of SQL from the credited upstream file 3268.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 EmployeeShifts5 UNION DISTINCT6 SELECT DISTINCT employee_id, end_time AS `time`7 FROM EmployeeShifts8 ),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 EmployeeShifts22 USING (employee_id)23 WHERE24 Segments.start_time >= EmployeeShifts.start_time25 AND Segments.end_time <= EmployeeShifts.end_time26 GROUP BY 1, 2, 327 )28SELECT29 employee_id,30 MAX(concurrent_count) AS max_overlapping_shifts,31 SUM(32 concurrent_count * (concurrent_count - 1) / 2 * TIMESTAMPDIFF(33 MINUTE,34 start_time,35 end_time36 )37 ) AS total_overlap_duration 38FROM SegmentsCount39GROUP BY 140ORDER BY 1;41