https://cwiki.apache.org/confluence/display/Hive/LanguageManual+Select
查詢語句語法:
[WITH CommonTableExpression (, CommonTableExpression)*] (Note: Only available
starting with Hive 0.13.0)
SELECT [ALL | DISTINCT] select_expr, select_expr, ...
FROM table_reference
[WHERE where_condition]
[GROUP BY col_list]
[ORDER BY col_list]
[CLUSTER BY col_list
| [DISTRIBUTE BY col_list] [SORT BY col_list]
]
[LIMIT number]
全表和特定列查詢
創建部門表
create table if not exists dept(
deptno int,
dname string,
loc int
)
row format delimited fields terminated by '\t';
創建員工表
create table if not exists emp(
empno int,
ename string,
job string,
mgr int,
hiredate string,
sal double,
comm double,
deptno int)
row format delimited fields terminated by '\t';
導入數據
hive (default)> load data local inpath '/opt/module/datas/dept.txt' into table dept;
hive (default)> load data local inpath '/opt/module/datas/emp.txt' into table emp;
全表查詢
hive (default)> select * from emp;
選擇特定列查詢
hive (default)> select empno, ename from emp;
注意:
- SQL 語言大小寫不敏感。
- SQL 可以寫在一行或者多行
- 關鍵字不能被縮寫也不能分行
- 各子句一般要分行寫。
- 使用縮進提高語句的可讀性。
列別名
- 重命名一個列
- 便於計算
- 緊跟列名,也可以在列名和別名之間加入關鍵字‘AS’
- 案例實操
查詢名稱和部門
hive (default)> select ename AS name, deptno dn from emp;
算術運算符
運算符 | 描述 |
---|---|
A+B | A和B 相加 |
A-B | A減去B |
A*B | A和B 相乘 |
A/B | A除以B |
A%B | A對B取餘 |
A&B | A和B按位取與 |
A|B | A和B按位取或 |
A^B | A和B按位取異或 |
~A | A按位取反 |
案例實操
查詢出所有員工的薪水後加1顯示。
hive (default)> select sal +1 from emp;
常用函數
- 求總行數(count)
hive (default)> select count(*) cnt from emp;
- 求工資的最大值(max)
hive (default)> select max(sal) max_sal from emp;
- 求工資的最小值(min)
hive (default)> select min(sal) min_sal from emp;
- 求工資的總和(sum)
hive (default)> select sum(sal) sum_sal from emp;
- 求工資的平均值(avg)
hive (default)> select avg(sal) avg_sal from emp;
Limit語句
典型的查詢會返回多行數據。LIMIT子句用於限制返回的行數。
hive (default)> select * from emp limit 5;
簡書:https://www.jianshu.com/u/0278602aea1d
CSDN:https://blog.csdn.net/u012387141