SELECT
    CONCAT(DATE(t_stamp), ' ', LPAD(HOUR(t_stamp), 2, '0'), ':00') AS `Start Timestamp`,
    CONCAT('H', TIMESTAMPDIFF(HOUR, DATE_FORMAT(t_stamp, "%Y-%m-%d %H:00:00"), DATE_FORMAT(NOW(), "%Y-%m-%d %H:00:00"))) AS `Hour`,
    COUNT(*) AS `Total`,
    SUM(CASE WHEN adiSort_Code_0 = 0 THEN 1 ELSE 0 END) AS `Sorted`,
    SUM(CASE WHEN adiSort_Code_0 = 1 THEN 1 ELSE 0 END) AS `Unknown`,
    SUM(CASE WHEN adiSort_Code_0 = 2 THEN 1 ELSE 0 END) AS `Unexpected`,
    SUM(CASE WHEN adiSort_Code_0 = 3 THEN 1 ELSE 0 END) AS `TrackingError`,
    SUM(CASE WHEN adiSort_Code_0 = 4 THEN 1 ELSE 0 END) AS `GapError`,
    SUM(CASE WHEN adiSort_Code_0 = 5 THEN 1 ELSE 0 END) AS `DestinationFull`,
    SUM(CASE WHEN adiSort_Code_0 = 6 THEN 1 ELSE 0 END) AS `DestinationFault`,
    SUM(CASE WHEN adiSort_Code_0 = 7 THEN 1 ELSE 0 END) AS `DestinationInvalid`,
    SUM(CASE WHEN adiSort_Code_0 = 12 THEN 1 ELSE 0 END) AS `DestinationDisabled`,
    SUM(CASE WHEN adiSort_Code_0 = 13 THEN 1 ELSE 0 END) AS `ThroughputLimit`,
    SUM(CASE WHEN adiSort_Code_0 = 14 THEN 1 ELSE 0 END) AS `DivertFail`,
    SUM(CASE WHEN adiSort_Code_0 = 16 THEN 1 ELSE 0 END) AS `DestinationNone`,
    SUM(CASE WHEN adiSort_Code_0 = 17 THEN 1 ELSE 0 END) AS `Lost`,
    SUM(CASE WHEN adiSort_Code_0 = 18 THEN 1 ELSE 0 END) AS `DimensionError`,
    SUM(CASE WHEN adiSort_Code_0 = 19 THEN 1 ELSE 0 END) AS `WeightError`,
    SUM(CASE WHEN adiSort_Code_0 = 20 THEN 1 ELSE 0 END) AS `ContainerUtilization`,
    SUM(CASE WHEN adiSort_Code_0 = 21 THEN 1 ELSE 0 END) AS `UnableToDivert`,
    SUM(CASE WHEN adiSort_Code_0 = 22 THEN 1 ELSE 0 END) AS `DestinationNotAttempted`,
    SUM(CASE WHEN adiSort_Code_0 IN (8, 9, 10) THEN 1 ELSE 0 END) AS `ScanError`
FROM item_data
WHERE sActual_Dest_ID = :lane 
    AND t_stamp BETWEEN :starttime AND :endtime
    AND adiSort_Code_0 NOT IN (11, 15)
GROUP BY DATE(t_stamp), HOUR(t_stamp)
ORDER BY `Start Timestamp` ASC;

