📜  SQL-分类结果

📅  最后修改于: 2020-12-29 04:36:45             🧑  作者: Mango


SQL ORDER BY子句用于根据一个或多个列以升序或降序对数据进行排序。默认情况下,某些数据库将查询结果按升序排序。

句法

用于对结果进行升序或降序排序的ORDER BY子句的基本语法如下-

SELECT column-list 
FROM table_name 
[WHERE condition] 
[ORDER BY column1, column2, .. columnN] [ASC | DESC];

您可以在ORDER BY子句中使用多个列。确保无论您要使用什么列进行排序,该列都应在column-list中。

考虑具有以下记录的CUSTOMERS表-

+----+----------+-----+-----------+----------+
| 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的升序对结果进行排序。

SQL> SELECT * FROM CUSTOMERS
   ORDER BY NAME, SALARY;

这将产生以下结果-

+----+----------+-----+-----------+----------+
| 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的降序对结果进行排序。

SQL> SELECT * FROM CUSTOMERS
   ORDER BY NAME DESC;

这将产生以下结果-

+----+----------+-----+-----------+----------+
| 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 |
+----+----------+-----+-----------+----------+

要以自己的首选顺序获取行,使用的SELECT查询将如下所示-

SQL> SELECT * FROM CUSTOMERS
   ORDER BY (CASE ADDRESS
   WHEN 'DELHI'      THEN 1
   WHEN 'BHOPAL'      THEN 2
   WHEN 'KOTA'      THEN 3
   WHEN 'AHMEDABAD' THEN 4
   WHEN 'MP'     THEN 5
   ELSE 100 END) ASC, ADDRESS DESC;

这将产生以下结果-

+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
+----+----------+-----+-----------+----------+

这将首先按照您自己的偏好oorder中的ADDRESS对客户进行排序,并对其余地址按照自然顺序进行排序。同样,其余地址将按相反的字母顺序排序。