GROUP BY with JOIN produces unexpected results