SELECT
    roundtime AS `Round Time`,
    sScanner_Name AS `Scanner Name`,
    COALESCE(total_bad_reads, 0) AS `Total Bad Reads`,
    COALESCE(total_comm_faults, 0) AS `Total Comm Faults`,
    COALESCE(total_good_reads, 0) AS `Total Good Reads`,
    COALESCE(total_multi_items, 0) AS `Total Multi Items`,
    COALESCE(total_multi_reads, 0) AS `Total Multi Reads`,
    COALESCE(total_no_data, 0) AS `Total No Data`,
    COALESCE(total_no_reads, 0) AS `Total No Reads`,
    COALESCE(total_bad_reads, 0) + 
    COALESCE(total_comm_faults, 0) + 
    COALESCE(total_good_reads, 0) + 
    COALESCE(total_multi_items, 0) + 
    COALESCE(total_multi_reads, 0) + 
    COALESCE(total_no_data, 0) + 
    COALESCE(total_no_reads, 0) AS `Total`
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,
        sScanner_Name,
        SUM(diScanner_bad_reads) AS total_bad_reads,
        SUM(diScanner_comm_fault) AS total_comm_faults,
        SUM(diScanner_good_reads) AS total_good_reads,
        SUM(diScanner_multi_items) AS total_multi_items,
        SUM(diScanner_multi_reads) AS total_multi_reads,
        SUM(diScanner_no_data) AS total_no_data,
        SUM(diScanner_no_reads) AS total_no_reads
    FROM scanner_reads
    WHERE t_stamp BETWEEN :starttime AND :endtime
        AND (sScanner_Name = :scannername OR :scannername IS NULL OR :scannername = '')
    GROUP BY roundtime, sScanner_Name
    
    UNION ALL
    
    SELECT
        FROM_UNIXTIME(
            FLOOR(UNIX_TIMESTAMP(t_stamp) / 
                CEIL(TIMESTAMPDIFF(SECOND, :starttime, :endtime) / 24.0)
            ) * 
            CEIL(TIMESTAMPDIFF(SECOND, :starttime, :endtime) / 24.0)
        ) AS roundtime,
        'S02aa' AS sScanner_Name,
        SUM(CASE WHEN adiSort_Code_0 NOT IN (0, 8, 9, 10, 11, 15) THEN 1 ELSE 0 END) AS total_bad_reads,
        0 AS total_comm_faults,
        SUM(CASE WHEN adiSort_Code_0 = 0 THEN 1 ELSE 0 END) AS total_good_reads,
        0 AS total_multi_items,
        SUM(CASE WHEN adiSort_Code_0 = 10 THEN 1 ELSE 0 END) AS total_multi_reads,
        SUM(CASE WHEN adiSort_Code_0 = 9 THEN 1 ELSE 0 END) AS total_no_data,
        SUM(CASE WHEN adiSort_Code_0 = 8 THEN 1 ELSE 0 END) AS total_no_reads
    FROM item_data
    WHERE t_stamp BETWEEN :starttime AND :endtime
        AND adiSort_Code_0 NOT IN (11, 15)
        AND sLocation_ID LIKE 'S02%'
        AND (:scannername IS NULL OR :scannername = '' OR :scannername = 'S02aa')
    GROUP BY roundtime
    ORDER BY roundtime ASC
) basa;
