按案例排序
如果要按数字或字母顺序对数据进行排序,只需使用 order by [column]
即可。如果要使用自定义层次结构进行排序,请使用 case 语句。
GroupTotal
Young
MiddleAge
Old
Male
Female
使用基本的 order by
:
Select * from MyTable
Order by Group
返回按字母顺序排序,这并不总是令人满意的:
GroupFemale
Male
MiddleAge
Old
Total
Young
添加’case’语句,按照你希望数据排序的顺序分配升序数值:
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
按指定的顺序返回数据:
GroupTotal
Male
Female
Young
MiddleAge
Old