T Sql 简明教程
T-SQL - ORDER BY Clause
MS SQL Server ORDER BY 子句用于按一个或多个列基于升序或降序对数据进行排序。默认情况下,一些数据库按升序对查询结果进行排序。
The MS SQL Server ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some database sort query results in ascending order by default.
Syntax
以下是 ORDER BY 子句的基本语法。
Following is the basic syntax of ORDER BY clause.
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
你可以在 ORDER BY 子句中使用多个列。确保要用于排序的列在列列表中。
You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort, that column should be in column-list.
Example
考虑包含以下记录的 CUSTOMERS 表:
Consider the CUSTOMERS table having the following records −
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
以下命令是一个示例,按 NAME 和 SALARY 升序对结果进行排序。
Following command is an example, which would sort the result in ascending order by NAME and SALARY.
SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY
以上命令将生成以下输出。
The above command will produce the following output.
ID NAME AGE ADDRESS SALARY
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
3 kaushik 23 Kota 2000.00
2 Khilan 25 Delhi 1500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
1 Ramesh 32 Ahmedabad 2000.00
以下命令是一个示例,按 NAME 降序对结果进行排序。
Following command is an example, which would sort the result in descending order by NAME.
SELECT * FROM CUSTOMERS
ORDER BY NAME DESC
以上命令将生成以下结果 −
The above command will produce the following result −
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
7 Muffy 24 Indore 10000.00
6 Komal 22 MP 4500.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
5 Hardik 27 Bhopal 8500.00
4 Chaitali 25 Mumbai 6500.00