查询(重点)
查询的基本语法
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]
分组查询
分组使用的语句是Group By语句
①Group By
GROUP BY语句通常会和聚合函数一起使用,按照一个或者多个列队结果进行分组,然后对每个组执行聚合操作
Group可以对一个列进行分组,也可以对多个列进行分组
1)对一个列进行分组
查询每个部门的平均工资
select deptno, avg(sal) dept_sal from emp group by deptno;
2)对多个列进行分组
查询每个部门每个工作的最高工资
select deptno, job, max(sal) max_sal from emp group by depton, job;
在这里插入图片描述
②Having语句
having与where不同点:
(1)where后面不能写聚合函数,而having后面可以使用聚合函数。
(2)having只用于group by分组统计语句。
查找每个部门平均工资大于2000的部门
select deptno, avg(sal) avg_sal from emp group by deptno having avg_sal>2000;