Home > Back-end >  Ordering data alphabetically into two groups
Ordering data alphabetically into two groups

Time:11-12

I have the following table (players) for which I wish to rank the names alphabetically and then sort them into two teams, 1 and 2. So, as "Kaaleppi" is first alphabetically, he will be assigned to Team 1, Liisa is second alphabetically so she will be assigned to team 2 etc.

Data (players) :

enter image description here

Result wanted:

enter image description here

I am able to order the data alphabetically but I can't figure out how to sort them into teams:

SELECT * FROM Players ORDER BY name ASC

CodePudding user response:

You can try the following, provided your database supports windowing functions

select Name, case Row_Number() over(order by Name) % 2 when 1 then 1 else 2 end
from players
order by name
  • Related