SELECT 
    COALESCE(data.roundtime, 'N/A') AS StartTimestamp,
    COALESCE(CONCAT('H', TIMESTAMPDIFF(HOUR, DATE_FORMAT(data.roundtime, "%Y-%m-%d %H:00:00"), DATE_FORMAT(NOW(), "%Y-%m-%d %H:00:00"))), 'N/A') AS Hour,
    COALESCE(data.sInduction_Name, 'N/A') AS sInduction_Name,
    COALESCE(data.SingleCarrier_percent, '0%') AS SingleCarrier_percent,
    COALESCE(data.DoubleCarrier_percent, '0%') AS DoubleCarrier_percent,
    COALESCE(data.Total_count, 0) AS Total_count
FROM (SELECT 1) AS p
LEFT JOIN (
    SELECT 
        CONCAT(DATE(t_stamp), ' ', HOUR(t_stamp), ':00') AS roundtime,
        sInduction_Name,
        CONCAT(
            CASE 
                WHEN (COALESCE(SUM(diTotal_Single_Carrier), 0) + COALESCE(SUM(diTotal_Double_Carrier), 0)) = 0 THEN 0
                ELSE ROUND((COALESCE(SUM(diTotal_Single_Carrier), 0) * 100.0) / (
                    COALESCE(SUM(diTotal_Single_Carrier), 0) + COALESCE(SUM(diTotal_Double_Carrier), 0)
                ), 2)
            END, '%'
        ) AS SingleCarrier_percent,
        CONCAT(
            CASE 
                WHEN (COALESCE(SUM(diTotal_Single_Carrier), 0) + COALESCE(SUM(diTotal_Double_Carrier), 0)) = 0 THEN 0
                ELSE ROUND((COALESCE(SUM(diTotal_Double_Carrier), 0) * 100.0) / (
                    COALESCE(SUM(diTotal_Single_Carrier), 0) + COALESCE(SUM(diTotal_Double_Carrier), 0)
                ), 2)
            END, '%'
        ) AS DoubleCarrier_percent,
        COALESCE(SUM(diTotal_Single_Carrier), 0) + COALESCE(SUM(diTotal_Double_Carrier), 0) AS Total_count
    FROM induction_data
    WHERE t_stamp BETWEEN :starttime AND :endtime
        AND (sInduction_Name = :inductionname OR :inductionname IS NULL OR :inductionname = '')
    GROUP BY DATE(t_stamp), HOUR(t_stamp), sInduction_Name
    
    UNION ALL
    
    SELECT 
        CONCAT(DATE(t_stamp), ' ', HOUR(t_stamp), ':00') AS roundtime,
        'S02' AS sInduction_Name,
        '100%' AS SingleCarrier_percent,
        '0%' AS DoubleCarrier_percent,
        COUNT(*) AS Total_count
    FROM item_data
    WHERE t_stamp BETWEEN :starttime AND :endtime
        AND adiSort_Code_0 NOT IN (11, 15)
        AND sLocation_ID LIKE 'S02%'
        AND (:inductionname IS NULL OR :inductionname = '' OR :inductionname = 'S02')
    GROUP BY DATE(t_stamp), HOUR(t_stamp)
) AS data ON 1=1
ORDER BY data.roundtime ASC;
