All problems · Conditional aggregation
Line-level totals that reconcile to the network
Return delay totals for raw BD, SHP, SRT and YU, bucket every other value including NULL into OTHER, and show the grand total last.
Source
Data: TTC Subway Delay Data (City of Toronto, 2023 snapshot), licence, read 2026-11-29.
Schema
incident(id INTEGER, service_date TEXT, clock_time TEXT, weekday TEXT, station TEXT, code TEXT, delay INTEGER, gap INTEGER, bound TEXT, line TEXT, vehicle INTEGER); delay_code(code TEXT, description TEXT). One incident row is one workbook record, not necessarily a unique event. Dates are ISO YYYY-MM-DD; id is the 1-based data row ordinal. Delay and gap are recorded minutes; gap is time between trains. Blank bound and line values remain NULL; zero values and raw labels are preserved. IDs identify source rows, not riders. Contains information licensed under the Open Government Licence – Toronto.
Show the checked solution
SQL
WITH a AS
(SELECT CASE
WHEN line IN ('BD',
'SHP',
'SRT',
'YU') THEN line
ELSE 'OTHER'
END AS bucket,
delay
FROM incident),
b AS
(SELECT bucket,
sum(delay) AS delay_minutes,
0 AS total_row
FROM a
GROUP BY bucket
UNION ALL SELECT 'TOTAL',
sum(delay),
1
FROM a)
SELECT bucket,
delay_minutes
FROM b
ORDER BY total_row,
bucket;
Expected output
| bucket | delay_minutes |
|---|---|
| BD | 24459 |
| OTHER | 28 |
| SHP | 2855 |
| SRT | 4839 |
| YU | 35998 |
| TOTAL | 68179 |