查询语法
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 [offset,] rows]
- 示例
select id,name
from hive.test
where id > 2
group by
注意:
- SQL语言大小写不敏感
- SQL可以写在一行多行,一般各字句分行写
- 关键字不能缩写或分行写
SQL书写顺序
select ... from ...where...group by...
ordered by | distribute by | sort by...cluster by...
limit rows
SQL执行顺序
- 可以使用
explain来查看执行计划 - 如:explain select * from stu;
from ..on .. join .. .. where .. select .. group by
.. having .. order by
基础查询
查询全表和特定列
select id,name from stu;
例起别名
- 重命名一个列。别名紧跟原列名,别名和原列名直接可加入关键字
as,不建议省略。
select id,name as stuName from stu;
常用函数
- count:行数统计函数
- count()和count(1)效率差别不大,SQL会自动优化count()不会做权标扫描
- 但是某些版本必须使用count(1),所以建议使用count(1)查询
# 求总行数,包含该NULL行
select count(*) from score;
# 求总行数,包含该NULL行
select count(1) [newColName] from score;
# 求指定列总行数,非NULL行总数
select count(name) [newColName] from score;
# 求指定列总行数,非NULL去重后的行总数(支持多个字段同时去重)
select count(distinct name1,name2....) from score;
# count支持和条件判断语句
count(CASE WHEN plat=1 THEN u ELSE NULL END),
count(DISTINCT CASE WHEN plat=1 THEN u ELSE NULL END)
- max:最大值统计函数
select max(s_score) from score;
- min:最小值统计函数
select min(s_score) from score;
- sum:总和统计函数,结果和order by相关,默认为升序。
# 求指定列结果累加之和
select sum(s_score) from score;
# 求指定行列结果去重之和累加之和
select sum(distinct s_score) from score;
- avg:平均值统计函数
# 求指定列平均值
select avg(s_score) from score;
# 求指定列去重之和的平均值
select avg(distinct s_score) from score;
1647

被折叠的 条评论
为什么被折叠?



