sqlselectalphabetical

How can I sort data into 3 alphabetical subgroups with SQL?


I'm displaying student data for teachers at my school using SQL, and for usability reasons it needs to be displayed with very unique sorting, with 3 subsets of the alphabet dividing the dataset, then normal sorting within that.

It should spit out something like this:

Last names A-F, sorted by period, then by last name

Last names G-O, sorted by period, then by last name

Last names P-Z, sorted by period, then by last name

It's currently sorted by period and last name fairly simply, and I can use three different queries to split the data as such, but I don't know how to do it all in one.

SELECT * FROM Student ORDER BY per, last;

Solution

  • Are you looking for a conditional expression in the order by?

    order by (case when last < 'G' then 1
                   when last < 'P' then 2
                   else 3
              end),
             per, last