WITH INDUCTS AS ( ( SELECT MIN(s04_timestamp) AS start_timestamp, MAX(s04_timestamp) AS end_timestamp, sorter, induct, COUNT(*) AS total FROM package_history WHERE s04_timestamp BETWEEN :startDate AND :endDate GROUP BY sorter, induct ) UNION ALL ( SELECT MIN(timestamp) AS start_timestamp, MAX(timestamp) AS end_timestamp, "AR" AS sorter, lane_id AS induct, SUM(count) AS total FROM pe_history WHERE timestamp BETWEEN :startDate AND :endDate AND lane_id LIKE "UL%" GROUP BY lane_id ) ORDER BY sorter, induct ), SORTERS AS ( SELECT sorter, 3600/TIMESTAMPDIFF(SECOND, :startDate, :endDate) AS pph_multiplier, SUM(total) AS total FROM INDUCTS GROUP BY sorter ) SELECT I.start_timestamp, I.end_timestamp, S.sorter, I.induct, /* Counts: */ I.total AS total_count, /* PPH: */ ROUND(I.total*S.pph_multiplier) AS total_pph, /* Percents: */ ROUND(I.total/S.total, 4) AS 'total/sorter_percent' FROM INDUCTS I, SORTERS S WHERE I.sorter = S.sorter ORDER BY sorter, induct;