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