12 group by 与 having

group by 

分组函数与字段

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

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

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

例如:

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

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;

猜你喜欢

转载自www.cnblogs.com/Scorpicat/p/12295291.html
今日推荐