-- Fixed Count Query
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,
        SUM(diTotal_Single_Carrier) AS total_single_carrier,
        SUM(diTotal_Double_Carrier) AS total_double_carrier,
        (
            COALESCE(SUM(diTotal_Single_Carrier), 0) +
            COALESCE(SUM(diTotal_Double_Carrier), 0)
        ) AS total
    FROM induction_data
    WHERE t_stamp BETWEEN TIMESTAMP(:starttime) AND TIMESTAMP(: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,
    COALESCE(sorter_total.total, 0) AS total
FROM (SELECT 1) AS p
LEFT JOIN (
    SELECT
        COUNT(*) AS total
    FROM item_data
    WHERE t_stamp BETWEEN TIMESTAMP(:starttime) AND TIMESTAMP(:endtime)
        AND adiSort_Code_0 NOT IN (11, 15)
        AND sLocation_ID LIKE 'S02%'
) AS sorter_total ON 1=1;

