SQL ORDER BY

SQL ORDER BY 子句对结果集进行排序,它只能用于 SQL SELECT 语句。

SQL ORDER BY 语法

SELECT Columns
FROM 数据表
ORDER BY Column1 ASC|DESC {, Column2 ASC|DESC}+

The {}+ 表示我们可以重复一或多次。
ACS 表示对结果集进行升序排列。
DESC 表示对结果集进行倒序排列。
默认是升序排列 (ASC)。

SQL ORDER BY 范例

数据表: Employees

EmployeeId FirstName LastName Department Salary
203 Mazojys Fxoj Finance 78000
204 Jozzh Lnanyo Finance 45800
205 Syllauu Dfaafk Finance 55000
206 Gecrrcc Srlkrt Finance 75000
302 Jssme Bdnaa Development 75000
303 Dnnaao Errllov Development 55000
304 Tyoysww Osk Development 49000

例1
选择所有记录并以工资为序排列:

SELECT *
FROM Employees
ORDER BY Salary

结果会类似于:

EmployeeId FirstName LastName Department Salary
204 Jozzh Lnanyo Finance 45800
304 Tyoysww Osk Development 49000
205 Syllauu Dfaafk Finance 55000
303 Dnnaao Errllov Development 55000
206 Gecrrcc Srlkrt Finance 75000
302 Jssme Bdnaa Development 75000
203 Mazojys Fxoj Finance 78000

例2
选择所有记录,但以工资为序倒序排列:

SELECT *
FROM Employees
ORDER BY Salary DESC

结果会类似于:

EmployeeId FirstName LastName Department Salary
203 Mazojys Fxoj Finance 78000
206 Gecrrcc Srlkrt Finance 75000
302 Jssme Bdnaa Development 75000
205 Syllauu Dfaafk Finance 55000
303 Dnnaao Errllov Development 55000
304 Tyoysww Osk Development 49000
204 Jozzh Lnanyo Finance 45800

例3
选择所有记录,以工资为序排列,如果工资相同,以LastName为序排列:

SELECT *
FROM Employees
ORDER BY Salary, LastName

结果会类似于:

EmployeeId FirstName LastName Department Salary
204 Jozzh Lnanyo Finance 45800
304 Tyoysww Osk Development 49000
205 Syllauu Dfaafk Finance 55000
303 Dnnaao Errllov Development 55000
302 Jssme Bdnaa Development 75000
206 Gecrrcc Srlkrt Finance 75000
203 Mazojys Fxoj Finance 78000