MySQL——分组查询

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

内容简介:按照性别将班上同学分为男生一组,女生一组。因为分组函数是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——分组查询


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

查看所有标签

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

Modeling the Internet and the Web

Modeling the Internet and the Web

Pierre Baldi、Paolo Frasconi、Padhraic Smyth / Wiley / 2003-7-7 / USD 115.00

Modeling the Internet and the Web covers the most important aspects of modeling the Web using a modern mathematical and probabilistic treatment. It focuses on the information and application layers, a......一起来看看 《Modeling the Internet and the Web》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器