12 group by 与 having

group by 

分组函数与字段

分组函数有 avg sum max min等,select时它们返回的是一个具体的值,而select一个字段返回的是一条记录。

所以当分组函数与字段同时出现,就需要分组,否则会报错

出现的字段都必须分组,没有出现的也可以分组。

例如:

select count(*),job,ename from emp group by job,ename;

可以这样去理解:分完组后,每个组中有对应的记录,可以对他们进行sum avg max min等操作。这些操作都是与group by 一起写的。

而且 select 后面有字段和分组函数时,字段不能写 .* ,必须写清楚

where 与 having

where 与 having 都用来筛选,区别是:

where 用在对字段进行筛选。

having 用在 有分组函数时(必须有) 对分组函数进行筛选,且不能用having 对字段进行筛选。

例如:

--查询不同部门的不同工作岗位且人数大于1的信息:使用having
select count(*),deptno,job from emp group by deptno,job having count(*)>1 order by deptno;

举个例子

--16、统计平均工资大于2000的部门的详细信息
select d.deptno,dname,loc,avg(sal) "平均工资" from dept d
join emp e
on d.deptno=e.deptno
group by d.deptno,dname,loc
having  avg(sal) >2000;

  

原文地址:https://www.cnblogs.com/Scorpicat/p/12295291.html