SELECT
    Name,
    COALESCE(Jam_rate, 0) AS Jam_rate
FROM (
    SELECT
        FROM_UNIXTIME(
            FLOOR(UNIX_TIMESTAMP(t_stamp) / 
                CEIL(TIMESTAMPDIFF(SECOND, :starttime, :endtime) / 24.0)
            ) * 
            CEIL(TIMESTAMPDIFF(SECOND, :starttime, :endtime) / 24.0)
        ) AS roundtime,
        Name,
        CASE 
            WHEN TIMESTAMPDIFF(SECOND, :starttime, :endtime) = 0 THEN 0
            ELSE ROUND(COUNT(*) * 3600.0 / TIMESTAMPDIFF(SECOND, :starttime, :endtime), 2)
        END AS Jam_rate
    FROM (
        -- Jams from jam_area table
        SELECT Name, t_stamp
        FROM jam_area
        WHERE t_stamp BETWEEN :starttime AND :endtime

        UNION ALL

        -- Jams from lane_data table (only where Jam = 1)
        SELECT Name, t_stamp
        FROM lane_data
        WHERE t_stamp BETWEEN :starttime AND :endtime
          AND Jam = 1
    ) AS combined_jams
    GROUP BY Name  -- << changed here: now grouped only by Name
) basa
ORDER BY Jam_rate DESC, Name ASC;
