If you want to sort your data numerically or alphabetically, you can simply use order by [column]
. If you want to sort using a custom hierarchy, use a case statement.
Group
-----
Total
Young
MiddleAge
Old
Male
Female
Using a basic order by
:
Select * from MyTable
Order by Group
returns an alphabetical sort, which isn't always desirable:
Group
-----
Female
Male
MiddleAge
Old
Total
Young
Adding a 'case' statement, assigning ascending numerical values in the order you want your data sorted:
Select * from MyTable
Order by case Group
when 'Total' then 10
when 'Male' then 20
when 'Female' then 30
when 'Young' then 40
when 'MiddleAge' then 50
when 'Old' then 60
end
returns data in the order specified:
Group
-----
Total
Male
Female
Young
MiddleAge
Old