HiveQL Select Order By
本章介绍如何在 SELECT 语句中使用 ORDER BY 子句。
ORDER BY子句用于基于一列检索信息,并按升序或降序对结果集进行排序。
语法
下面给出的是ORDER BY子句的语法:
SELECT [ALL | DISTINCT] select_expr, select_expr, ... FROM table_reference [WHERE where_condition] [GROUP BY col_list] [HAVING having_condition] [ORDER BY col_list]] [LIMIT number];
范例
让我们以SELECT ... ORDER BY子句为例。使用名称为Id,Name,Salary,Designation和Dept的字段假设如下所示的员工表。生成一个查询以使用部门名称按顺序检索员工详细信息。
+------+--------------+-------------+-------------------+--------+ | ID | Name | Salary | Designation | Dept | +------+--------------+-------------+-------------------+--------+ |1201 | Gopal | 45000 | Technical manager | TP | |1202 | Manisha | 45000 | Proofreader | PR | |1203 | Masthanvali | 40000 | Technical writer | TP | |1204 | Krian | 40000 | Hr Admin | HR | |1205 | Kranthi | 30000 | Op Admin | Admin | +------+--------------+-------------+-------------------+--------+
以下查询使用上述方案检索员工详细信息:
hive> SELECT Id, Name, Dept FROM employee ORDER BY DEPT;
成功执行查询后,您将看到以下响应:
+------+--------------+-------------+-------------------+--------+ | ID | Name | Salary | Designation | Dept | +------+--------------+-------------+-------------------+--------+ |1205 | Kranthi | 30000 | Op Admin | Admin | |1204 | Krian | 40000 | Hr Admin | HR | |1202 | Manisha | 45000 | Proofreader | PR | |1201 | Gopal | 45000 | Technical manager | TP | |1203 | Masthanvali | 40000 | Technical writer | TP | +------+--------------+-------------+-------------------+--------+
JDBC 程序
这是用于给定示例应用Order By子句的JDBC程序。
import java.sql.SQLException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.Statement; import java.sql.DriverManager; public class HiveQLOrderBy { private static String driverName = "org.apache.hadoop.hive.jdbc.HiveDriver"; public static void main(String[] args) throws SQLException { // Register driver and create driver instance Class.forName(driverName); // get connection Connection con = DriverManager.getConnection("jdbc:hive://localhost:10000/userdb", "", ""); // create statement Statement stmt = con.createStatement(); // execute statement Resultset res = stmt.executeQuery("SELECT * FROM employee ORDER BY DEPT;"); System.out.println(" ID \t Name \t Salary \t Designation \t Dept "); while (res.next()) { System.out.println(res.getInt(1) + " " + res.getString(2) + " " + res.getDouble(3) + " " + res.getString(4) + " " + res.getString(5)); } con.close(); } }
将程序保存在名为HiveQLOrderBy.java的文件中。使用以下命令来编译和执行该程序。
$ javac HiveQLOrderBy.java $ java HiveQLOrderBy
输出
ID Name Salary Designation Dept 1205 Kranthi 30000 Op Admin Admin 1204 Krian 40000 Hr Admin HR 1202 Manisha 45000 Proofreader PR 1201 Gopal 45000 Technical manager TP 1203 Masthanvali 40000 Technical writer TP 1204 Krian 40000 Hr Admin HR
本章解释 SELECT 语句中 GROUP BY 子句的细节。GROUP BY 子句用于使用特定的集合列对结果集中的所有记录进行分组。GROUP BY 子句用于查询一组记录。 语法GR ...