加油
每一天都是一次磨难的成长
group by 的理解与体会
Group By
从英文的字面意思上理解:根据(by)一定的规则进行分组(group).
定义:通过一定的规则将一个数据集划分成若干个小的区域,然后针对若干个小区域进行数据处理。
语法:
select 字段 from 表名 where 条件 group by 字段
or
select 字段 from 表名 group by 字段 having 过滤条件
注意:对于过滤条件,可以先用where,再用group by或者是先用group by,再用having
案列:
下面为案例代码:
使用数据库
use studentdb;
创建student表
create table student
(id int not null ,
name varchar(30),
grade varchar(30),
salary varchar(30)
);
在student表中插入数据
insert into student values(1,'zhangsan','A',1500);
insert into student values(2,'lisi','B',3000);
insert into student values(1,'zhangsan','A',1500);
insert into student values(4,'qianwu','A',3500);
insert into student values(3,'zhaoliu','C',2000);
insert into student values(1,'huyifei','D',2500);
图表如下:
1.单个字段的分组
1. 查出所有学生的等级(包括重复的等级)
SELECT grade FROM student;
2. 查出所有学生的等级(按照等级划分去除重复的元素)
SELECT grade FROM student GROUP BY grade;
2.多个字段的分组
SELECT name,sum(salary) FROM student GROUP BY name,grade;
配合聚合函数一起使用
常用的聚合函数:count(),avg(),max(),min(),sum()
count():计数
SELECT name,COUNT(*) FROM student GROUP BY name;
SELECT grade,count(*) FROM student GROUP BY grade;
sum():求和
SELECT name,SUM(salary) FROM student GROUP BY name,grade;
SELECT grade,sum(salary) FROM student GROUP BY grade;
avg():平均数
SELECT grade,avg(salary) FROM student GROUP BY grade;
max():最大值
SELECT grade,max(salary) FROM student GROUP BY grade;
min():最小值
SELECT grade,min(salary) FROM student GROUP BY grade;
对于这篇学习笔记就暂时到这了,兄弟们加油❤️🤣😂😊😘💕😍😒
从现在做起,坚持下去,一天进步一小点,不久的将来,你会感谢曾经努力的你!
👩🔧👨🔧🧑🔧
如果有出错的,请各位友友指正
本文含有隐藏内容,请 开通VIP 后查看