Step 1: the leaderboard. In a CTE per_trainer, count the badges of every trainer (0 for a trainer without badges — do not use the badges column of trainers). Then return badge_rank (a RANK() by badge count, highest first), name and badges, sorted by badge_rank then name.