MySQL——分组查询

栏目: 数据库 · 发布时间: 6年前

内容简介:按照性别将班上同学分为男生一组,女生一组。因为分组函数是sal,所以job不在分组函数中,必须出现在group by子句中

什么是分组

按照性别将班上同学分为男生一组,女生一组。

group by

/* 查看每个职位的最高、最低工资 */
select job,max(sale),min(sale) from emp group by job;

使用group by 语句

  • 出现在select列表中的字段,如果出现的位置不是分组函数,那么必须出现在group by子句中。

因为分组函数是sal,所以job不在分组函数中,必须出现在group by子句中

MySQL——分组查询

如果不出现,均出错!!!

MySQL——分组查询

MySQL——分组查询

  • 正确做法:
/* 查看不同职位的人数和平均工资 */
select job,count(empno),avg(sal) from emp group by job;
  • 错误做法:
/* deptno和job都应该出现在group by后面 */
select deptno,job,count(empno),avg(sal) from emp group by job;

group by子句后面不能含有where子句!!!

having

对分组的结果,进行筛选

/* 查询平均工资大于2000的部门和其平均工资 */
select deptho avg(sal) from emp group by deptno having avg(sal)>2000;

MySQL——分组查询

/* 显示每一年入职公司各多少人 */
select year(hiredate),count(empno) from emp group by year(hiredate);

MySQL——分组查询


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Cult of the Amateur

The Cult of the Amateur

Andrew Keen / Crown Business / 2007-6-5 / USD 22.95

Amateur hour has arrived, and the audience is running the show In a hard-hitting and provocative polemic, Silicon Valley insider and pundit Andrew Keen exposes the grave consequences of today’s......一起来看看 《The Cult of the Amateur》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

MD5 加密
MD5 加密

MD5 加密工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具