SELECT LEAST(source, dest), GREATEST(source, dest), SUM(IF(source < dest, source, 0)), SUM(IF(source < dest, dest, 0)) FROM tbl GROUP BY 1,2;