I have a weird table-sorting issue that I cannot figure out in Excel or SQL.
Here’s a table sorted by column 2, “Letter”.
Name | Letter |
---|---|
Dan | A |
Moe | A |
Ted | B |
Dan | C |
Joe | F |
Noe | F |
What I need is the table sorted by Letter BUT… if there are any duplicates in the “Name” column, I need those grouped–which would break the sorting in column 2. So below, even though the table is sorted by Letter, I want the two Dans together:
Name | Letter |
---|---|
Dan | A |
Dan | C |
Moe | A |
Ted | B |
Joe | F |
Noe | F |
Thanks for any help!
Advertisement
Answer
I would try something like this.
SELECT t.name, t.letter FROM table t JOIN (SELECT table.name, MIN(table.letter) AS min_letter_by_name FROM table GROUP BY table.name) ON t.name = table.name ORDER BY min_letter_by_name, name, letter