SELECT
    base.Total_Jam,
    base.Inbound_jam,
    base.Sorter_jam,
    base.Startstamp,
    base.Endtstamp,
    1 AS Total_perc,
    base.Inbound_jam / NULLIF(base.Total_Jam,0) AS Inbound_perc,
    base.Sorter_jam / NULLIF(base.Total_Jam,0) AS Sorter_perc
FROM (
    SELECT
        MIN(a.eventtime) AS Startstamp,
        MAX(COALESCE(c.eventtime, a.eventtime)) AS Endtstamp,
        SUM(a.category = 'Inbound_jam') AS Inbound_jam,
        SUM(a.category = 'Sorter_jam')  AS Sorter_jam,
        SUM(a.category IN ('Inbound_jam','Sorter_jam')) AS Total_Jam
    FROM (
        SELECT
            ae.id,
            ae.eventtime,
            ae.eventid,
            ae.displaypath AS device,
            m.category 
        FROM alarm_events ae
        JOIN (
            SELECT 'UL15_1_TPE1' AS device, 'Inbound_jam' AS category UNION ALL
            SELECT 'UL14_1_TPE1', 'Inbound_jam' UNION ALL
            SELECT 'PS3_1_TPE1', 'Inbound_jam' UNION ALL
            SELECT 'PS3_1_TPE2', 'Inbound_jam' UNION ALL
            SELECT 'PS3_1_TPE3', 'Inbound_jam' UNION ALL
            SELECT 'PS3_2_TPE1', 'Inbound_jam' UNION ALL
            SELECT 'PS3_4_TPE1', 'Inbound_jam' UNION ALL
            SELECT 'PS3_8_TPE1', 'Inbound_jam' UNION ALL
            SELECT 'PS3_10_TPE1', 'Inbound_jam' UNION ALL
            SELECT 'PS3_12_TPE1', 'Sorter_jam'
        ) AS m
        ON ae.displaypath = m.device
        WHERE ae.eventtype = 0
          AND ae.eventtime BETWEEN :starttime AND :endtime
          AND ae.displaypath NOT LIKE '%System Startup%'
          AND ae.source NOT LIKE '%System Startup%'
    ) AS a
    LEFT JOIN (
        SELECT eventid, MIN(eventtime) AS eventtime
        FROM alarm_events
        WHERE eventtype = 1
        GROUP BY eventid
    ) AS c
    ON a.eventid = c.eventid
) AS base;
