WITH latest AS (
    SELECT ld.*
    FROM lane_data ld
    INNER JOIN (
        SELECT Name, MAX(t_stamp) AS max_ts
        FROM lane_data
        WHERE Name LIKE 'S02\\_%'
        GROUP BY Name
    ) x ON ld.Name = x.Name AND ld.t_stamp = x.max_ts
),
classified AS (
    SELECT
        CASE
            WHEN Disabled = 1 THEN 'Disabled'
            WHEN Jam = 1 THEN 'Jammed'
            WHEN Full = 1 THEN '100% Full'
            WHEN Half_Full = 1 THEN '50% Full'
            ELSE 'Enabled'
        END AS category
    FROM latest
),
totals AS (
    SELECT COUNT(*) AS total_lanes FROM classified
),
agg AS (
    SELECT category, COUNT(*) AS category_count
    FROM classified
    GROUP BY category
),
all_categories AS (
    SELECT 'Enabled' AS category
    UNION ALL SELECT 'Disabled'
    UNION ALL SELECT 'Jammed'
    UNION ALL SELECT '50% Full'
    UNION ALL SELECT '100% Full'
)

SELECT
    ac.category,
    COALESCE(a.category_count, 0) AS Count,
    CONCAT(
        ROUND(COALESCE(a.category_count, 0) * 100.0 / (SELECT total_lanes FROM totals), 1),
        '%'
    ) AS `Percentage (%)`
FROM all_categories ac
LEFT JOIN agg a ON ac.category = a.category
ORDER BY FIELD(ac.category, 'Enabled', 'Disabled', 'Jammed', '50% Full', '100% Full');
