можно одним запросом сделать
$req = mysql_query("select `u2`.`name`, `u1`.`ref_id`, count(`u1`.`ref_id`) as `counref`
from `users` as `u1`
left join `users` as `u2`
on `u1`.`ref_id` = `u2`.`id`
where `u1`.`ref_id` <> 0
group by (`u1`.`ref_id`)
order by `counref` desc");
while ($res = mysql_fetch_array($req)) {
echo '<div>'.$res['name'].': '.$res['counref'].'</div>';
}