SELECT
    roundtime,
    sScanner_Name,
    CASE 
        WHEN interval_seconds = 0 THEN 0
        ELSE ROUND(COALESCE(total_bad_reads, 0) * 3600.0 / interval_seconds, 2)
    END AS total_bad_reads,
    CASE 
        WHEN interval_seconds = 0 THEN 0
        ELSE ROUND(COALESCE(total_comm_faults, 0) * 3600.0 / interval_seconds, 2)
    END AS total_comm_faults,
    CASE 
        WHEN interval_seconds = 0 THEN 0
        ELSE ROUND(COALESCE(total_good_reads, 0) * 3600.0 / interval_seconds, 2)
    END AS total_good_reads,
    CASE 
        WHEN interval_seconds = 0 THEN 0
        ELSE ROUND(COALESCE(total_multi_items, 0) * 3600.0 / interval_seconds, 2)
    END AS total_multi_items,
    CASE 
        WHEN interval_seconds = 0 THEN 0
        ELSE ROUND(COALESCE(total_multi_reads, 0) * 3600.0 / interval_seconds, 2)
    END AS total_multi_reads,
    CASE 
        WHEN interval_seconds = 0 THEN 0
        ELSE ROUND(COALESCE(total_no_data, 0) * 3600.0 / interval_seconds, 2)
    END AS total_no_data,
    CASE 
        WHEN interval_seconds = 0 THEN 0
        ELSE ROUND(COALESCE(total_no_reads, 0) * 3600.0 / interval_seconds, 2)
    END AS total_no_reads,
    CASE 
        WHEN interval_seconds = 0 THEN 0
        ELSE ROUND((
            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)
        ) * 3600.0 / interval_seconds, 2)
    END AS total
FROM (
    SELECT
        FROM_UNIXTIME(
            CEIL(UNIX_TIMESTAMP(t_stamp) / 
                GREATEST(3600, CEIL((UNIX_TIMESTAMP(:endtime) - UNIX_TIMESTAMP(:starttime)) / 24))
            ) * 
            GREATEST(3600, CEIL((UNIX_TIMESTAMP(:endtime) - UNIX_TIMESTAMP(:starttime)) / 24))
        ) AS roundtime,
        sScanner_Name,
        GREATEST(3600, CEIL((UNIX_TIMESTAMP(:endtime) - UNIX_TIMESTAMP(:starttime)) / 24)) AS interval_seconds,
        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
    ORDER BY roundtime ASC
) basa;

