SELECT
    'S01' AS Sorter,
    DATE_FORMAT(:starttime, '%Y-%m-%d %H:%i') AS start_time,
    DATE_FORMAT(:endtime, '%Y-%m-%d %H:%i') AS end_time,
    COALESCE(c.sInduction_Name, 'N/A') AS sInduction_Name,
    COALESCE(c.total_single_carrier, 0) AS total_single_carrier,
    COALESCE(c.total_double_carrier, 0) AS total_double_carrier,
    COALESCE(c.total, 0) AS total
FROM (SELECT 1) AS p
LEFT JOIN (
    SELECT
        sInduction_Name,
        CASE 
            WHEN TIMESTAMPDIFF(SECOND, :starttime, :endtime) = 0 THEN 0
            ELSE ROUND(COALESCE(SUM(diTotal_Single_Carrier), 0) * 3600.0 / TIMESTAMPDIFF(SECOND, :starttime, :endtime), 2)
        END AS total_single_carrier,
        CASE 
            WHEN TIMESTAMPDIFF(SECOND, :starttime, :endtime) = 0 THEN 0
            ELSE ROUND(COALESCE(SUM(diTotal_Double_Carrier), 0) * 3600.0 / TIMESTAMPDIFF(SECOND, :starttime, :endtime), 2)
        END AS total_double_carrier,
        CASE 
            WHEN TIMESTAMPDIFF(SECOND, :starttime, :endtime) = 0 THEN 0
            ELSE ROUND((COALESCE(SUM(diTotal_Single_Carrier), 0) + COALESCE(SUM(diTotal_Double_Carrier), 0)) * 3600.0 / TIMESTAMPDIFF(SECOND, :starttime, :endtime), 2)
        END AS total
    FROM induction_data
    WHERE t_stamp BETWEEN :starttime AND :endtime
    GROUP BY sInduction_Name
) AS c ON 1=1

UNION ALL

SELECT
    'S02' AS Sorter,
    DATE_FORMAT(:starttime, '%Y-%m-%d %H:%i') AS start_time,
    DATE_FORMAT(:endtime, '%Y-%m-%d %H:%i') AS end_time,
    'S02' AS sInduction_Name,
    0 AS total_single_carrier,
    0 AS total_double_carrier,
    CASE 
        WHEN TIMESTAMPDIFF(SECOND, :starttime, :endtime) = 0 THEN 0
        ELSE ROUND(COALESCE(sorter_total.total, 0) * 3600.0 / TIMESTAMPDIFF(SECOND, :starttime, :endtime), 2)
    END AS total
FROM (SELECT 1) AS p
LEFT JOIN (
    SELECT
        COUNT(*) AS total
    FROM item_data
    WHERE t_stamp BETWEEN :starttime AND :endtime
        AND adiSort_Code_0 NOT IN (11, 15)
        AND sLocation_ID LIKE 'S02%'
) AS sorter_total ON 1=1;

