十、GROUP BY 和 HAVING 的使用

简介: 十、GROUP BY 和 HAVING 的使用

一、group by 应用场景

在实际应用中我们会遇到如下的场景:


  • 公司想了解每个部门有多少员工;
  • 班主任想统计每科第一名的成绩;
  • 连锁店想知道每个门店男女员工的数量以及平均年龄。


这时我们就可以使用 group by 语句来解决这类需求。从字面上来理解,group by 表示根据某种规则对数据进行分组,他必须配合聚合函数进行使用,对数据进行分组后可以进行 countsumavgmax min 运算。语法如下:

SELECT column_name, aggregate_function(column_name) 
FROM table_name
GROUP BY column_name

TIP:

aggregate_function:表示聚合函数

group by :可以对一列或者多列进行分组


例如:

1. 查询出全校有多少名男学生和女学生

select sex, count(*) from student group by sex;

2. 查询每个班级有多少学生

select class, count(*) from student group by class;

3. 查询每个门店员工薪资总和

select dept,sum(salary) from employee group by dept;

二、having 的使用

在 SQL 中增加 HAVING 子句原因是, WHERE 关键子无法与聚合函数一起使用。 HAVING 子句可以对分组后的各组数据进行筛选。语法如下:

SELECT column_name,aggregate_funtion(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name
HAVING aggregate_function(column_name) operator value

例如:

1. 查询人数小于30人的班级

select class,count(*) from student group by class having count(*)<30

2. 查询每个门店薪资大于5000的员工

select dept,max(salary) from employee group by dept having max(salary)>5000
目录
相关文章
|
6月前
|
开发框架 .NET 编译器
C#-Group By 的使用
group by 是linq中的分组功能,能通过给定的字段对数据集进行分组,得到分组后的结果。
127 0
|
8月前
|
关系型数据库 MySQL Windows
Mysql (ONLY_FULL_GROUP_BY) Expression #1 of SELECT list is not in GROUP BY ...
Mysql (ONLY_FULL_GROUP_BY) Expression #1 of SELECT list is not in GROUP BY ...
62 0
|
10月前
|
SQL 关系型数据库 MySQL
GROUP BY和ORDER BY的区别
GROUP BY和ORDER BY的区别
239 0
|
11月前
|
SQL 关系型数据库 MySQL
only_full_group_by问题而引发的对group by的深入思考
only_full_group_by问题而引发的对group by的深入思考
104 0
|
SQL
ORDER BY && GROUP BY
ORDER BY && GROUP BY
61 0
ORDER BY && GROUP BY
group by+group_concat解决的小问题
group by+group_concat解决的小问题
77 0
group by
group by
66 0
|
SQL 关系型数据库 数据挖掘
你真的懂使用Group by?
你真的懂使用Group by?
463 0
你真的懂使用Group by?
new Grammar in 740 - Internal table group by
Created by Wang, Jerry, last modified on Sep 14, 2015
new Grammar in 740 - Internal table group by