📜  Impala-按条款排序

📅  最后修改于: 2020-11-30 05:04:36             🧑  作者: Mango


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

句法

以下是ORDER BY子句的语法。

select * from table_name ORDER BY col_name [ASC|DESC] [NULLS FIRST|NULLS LAST]

您可以分别使用关键字ASCDESC在表中按升序或降序排列数据。

同样,如果我们使用NULLS FIRST,则表中的所有空值都排列在最上面的行中;如果我们使用NULLS LAST,则包含空值的行将排在最后。

假设我们在数据库my_db中有一个名为客户的表,其内容如下-

[quickstart.cloudera:21000] > select * from customers;
Query: select * from customers 
+----+----------+-----+-----------+--------+ 
| id | name     | age | address   | salary | 
+----+----------+-----+-----------+--------+ 
| 3  | kaushik  | 23  | Kota      | 30000  | 
| 1  | Ramesh   |  32 | Ahmedabad | 20000  | 
| 2  | Khilan   | 25  | Delhi     | 15000  | 
| 6  | Komal    | 22  | MP        | 32000  | 
| 4  | Chaitali | 25  | Mumbai    | 35000  | 
| 5  | Hardik   | 27  | Bhopal    | 40000  | 
+----+----------+-----+-----------+--------+ 
Fetched 6 row(s) in 0.51s

以下是使用order by子句按客户编号升序排列客户表中数据的示例。

[quickstart.cloudera:21000] > Select * from customers ORDER BY id asc;

执行时,以上查询将产生以下输出。

Query: select * from customers ORDER BY id asc 
+----+----------+-----+-----------+--------+ 
| id | name     | age | address   | salary | 
+----+----------+-----+-----------+--------+ 
| 1  | Ramesh   | 32  | Ahmedabad | 20000  | 
| 2  | Khilan   | 25  | Delhi     | 15000  | 
| 3  | kaushik  | 23  | Kota      | 30000  | 
| 4  | Chaitali | 25  | Mumbai    | 35000  | 
| 5  | Hardik   | 27  | Bhopal    | 40000  | 
| 6  | Komal    | 22  | MP        | 32000  | 
+----+----------+-----+-----------+--------+ 
Fetched 6 row(s) in 0.56s

以相同的方式,您可以使用order by子句按以下降序排列customer表的数据,如下所示。

[quickstart.cloudera:21000] > Select * from customers ORDER BY id desc;

执行时,以上查询将产生以下输出。

Query: select * from customers ORDER BY id desc 
+----+----------+-----+-----------+--------+ 
| id | name     | age | address   | salary | 
+----+----------+-----+-----------+--------+ 
| 6  | Komal    | 22  | MP        | 32000  | 
| 5  | Hardik   | 27  | Bhopal    | 40000  | 
| 4  | Chaitali | 25  | Mumbai    | 35000  | 
| 3  | kaushik  | 23  | Kota      | 30000  | 
| 2  | Khilan   | 25  | Delhi     | 15000  |
| 1  | Ramesh   | 32  | Ahmedabad | 20000  | 
+----+----------+-----+-----------+--------+ 
Fetched 6 row(s) in 0.54s