-- Hourly Scanner Graph Query (Rate per hour)
-- Shows every hour in detail for graphing as rates (items per hour)

SELECT
    CONCAT('H', TIMESTAMPDIFF(HOUR,
        DATE_FORMAT(Startstamp, "%Y-%m-%d %H:00:00"),
        DATE_FORMAT(NOW(), "%Y-%m-%d %H:00:00")
    )) AS Hour,
    ROUND(COALESCE(Total, 0) * 3600 / GREATEST(TIMESTAMPDIFF(SECOND, Startstamp, Endtstamp), 1), 2) AS Total,
    ROUND(COALESCE(GoodRead, 0) * 3600 / GREATEST(TIMESTAMPDIFF(SECOND, Startstamp, Endtstamp), 1), 2) AS GoodRead,
    ROUND(COALESCE(NoRead, 0) * 3600 / GREATEST(TIMESTAMPDIFF(SECOND, Startstamp, Endtstamp), 1), 2) AS NoRead,
    ROUND(COALESCE(MultiRead, 0) * 3600 / GREATEST(TIMESTAMPDIFF(SECOND, Startstamp, Endtstamp), 1), 2) AS MultiRead,
    ROUND(COALESCE(NoCode, 0) * 3600 / GREATEST(TIMESTAMPDIFF(SECOND, Startstamp, Endtstamp), 1), 2) AS NoCode
FROM (
    SELECT
        MIN(t_stamp) AS Startstamp,
        MAX(t_stamp) AS Endtstamp,
        COUNT(*) AS Total,
        SUM(DivertStatus NOT IN (8, 9, 10)) AS GoodRead,
        SUM(DivertStatus = 8) AS NoRead,
        SUM(DivertStatus = 10) AS MultiRead,
        SUM(DivertStatus = 9) AS NoCode
    FROM alltable
    WHERE t_stamp BETWEEN :starttime AND :endtime
    GROUP BY DATE(t_stamp), HOUR(t_stamp)
) counts
ORDER BY Startstamp ASC;

