当前位置: 首页 > news >正文

【MySQL】聚合查询 和 分组查询

 个人主页:♡喜欢做梦

欢迎  👍点赞  ➕关注  ❤️收藏  💬评论


目录

🌴 一、聚合查询

🌲1.概念

🌲2.聚合查询函数

COUNT()

 SUM()

AVG()

 MAX()和MIN()

🌴 二、分组查询

🍀1.GROUP BY子句

定义

语法

 🍀2.HAVING

定义

having与where的区别

🌴 三、插入查询结果

🍃语法


🌴 一、聚合查询

🌲1.概念

聚合查询:是SQL中对数据进行分组统计的操作,可以将多行数据按照特定条件合并计算,返回汇总结果。

🌲2.聚合查询函数

函数说明
COUNT()统计行数
SUM()统计数值列总和
AVG()统计数值列平均和
MAX()寻找最大值
MIN()寻找最小值
  • 除了函数COUNT(),其他如果不是数字没有意义;
  • 除了函数COUNT(),可以进行全列COUNT(*)查询,其他不可以;
  • null不参与该查询;
  • 多个聚合函数可以同时使用。

示例: 

-- 创建学生成绩表
mysql>  create table student_grade(->  id bigint auto_increment primary key,->  name varchar(20),->  chinese bigint,->  math bigint,->  english bigint);
Query OK, 0 rows affected (0.07 sec)mysql> insert into student_grade(name,chinese,math,english) values('张三',89,95,65),-> ('李四',96,88,67),('王柿子',78,91,75),('张亮',99,73,97);
Query OK, 4 rows affected (0.13 sec)
Records: 4  Duplicates: 0  Warnings: 0mysql> insert into student_grade(name,chinese,math,english) values('丽丽',null,56,89);
Query OK, 1 row affected (0.05 sec)mysql> select* from student_grade;
+----+-----------+---------+------+---------+
| id | name      | chinese | math | english |
+----+-----------+---------+------+---------+
|  1 | 张三      |      89 |   95 |      65 |
|  2 | 李四      |      96 |   88 |      67 |
|  3 | 王柿子    |      78 |   91 |      75 |
|  4 | 张亮      |      99 |   73 |      97 |
|  5 | 丽丽      |    NULL |   56 |      89 |
+----+-----------+---------+------+---------+
5 rows in set (0.00 sec)

COUNT()

mysql> select* from student_grade;
+----+-----------+---------+------+---------+
| id | name      | chinese | math | english |
+----+-----------+---------+------+---------+
|  1 | 张三      |      89 |   95 |      65 |
|  2 | 李四      |      96 |   88 |      67 |
|  3 | 王柿子    |      78 |   91 |      75 |
|  4 | 张亮      |      99 |   73 |      97 |
|  5 | 丽丽      |    NULL |   56 |      89 |
+----+-----------+---------+------+---------+
5 rows in set (0.00 sec)-- 推荐使用COUNT(*)查询
mysql> select count(*) from student_grade;
+----------+
| count(*) |
+----------+
|        5 |
+----------+
1 row in set (0.00 sec)-- 当然,也可以使用常量
mysql>  select count(1) from student_grade;
+----------+
| count(1) |
+----------+
|        5 |
+----------+
1 row in set (0.00 sec)-- 可以指定列查询,因为chinese中有null,这不会被统计在内
mysql> select count(chinese) from student_grade;
+----------------+
| count(chinese) |
+----------------+
|              4 |
+----------------+
1 row in set (0.00 sec)
  • 一般使用COUNT(*)来查询,里面也可以使用常量,当更推荐使用*;
  • 也可以指定列查询;
  • 当列中包含null,null不会被统计在内。 

 SUM()

mysql> select* from student_grade;
+----+-----------+---------+------+---------+
| id | name      | chinese | math | english |
+----+-----------+---------+------+---------+
|  1 | 张三      |      89 |   95 |      65 |
|  2 | 李四      |      96 |   88 |      67 |
|  3 | 王柿子    |      78 |   91 |      75 |
|  4 | 张亮      |      99 |   73 |      97 |
|  5 | 丽丽      |    NULL |   56 |      89 |
+----+-----------+---------+------+---------+
5 rows in set (0.00 sec)-- 查询数学成绩总和
mysql> select sum(math) from student_grade;
+-----------+
| sum(math) |
+-----------+
|       403 |
+-----------+
1 row in set (0.03 sec)-- 参数可以使用表达式
mysql> select sum(math+chinese+english) as total from student_grade;
+-------+
| total |
+-------+
|  1013 |
+-------+
1 row in set (0.04 sec)-- 查询语文成绩总和
-- 之前说到null与任何值结果相加都为null,chinese有null值但是其结果并不为null
-- 原因:在sum()求和时,null不参与运算
mysql> select sum(chinese) from student_grade;
+--------------+
| sum(chinese) |
+--------------+
|          362 |
+--------------+
1 row in set (0.00 sec)-- *一般用来取所有列,不能直接用在sun()函数里
mysql> select sum(*) from student_grade;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*) from student_grade' at line 1
  • *不能直接使用sum()函数里面,一般用于计算某一列中数值的总和,也就是SUM(列名);
  • 参数可以使用表达式;
  • null不参与SUM()运算。 

AVG()

-- 查询语文成绩平均值
mysql>  select avg(chinese) from student_grade;
+--------------+
| avg(chinese) |
+--------------+
|      90.5000 |
+--------------+
1 row in set (0.00 sec)-- 查询数学成绩平均值
mysql> select avg(math) from student_grade;
+-----------+
| avg(math) |
+-----------+
|   80.6000 |
+-----------+
1 row in set (0.00 sec)-- 不能使用*
mysql> select avg(*) from student_grade;
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*) from student_grade' at line 1
  • 其注意事项与SUM()相似 

 MAX()和MIN()

mysql> select* from student_grade;
+----+-----------+---------+------+---------+
| id | name      | chinese | math | english |
+----+-----------+---------+------+---------+
|  1 | 张三      |      89 |   95 |      65 |
|  2 | 李四      |      96 |   88 |      67 |
|  3 | 王柿子    |      78 |   91 |      75 |
|  4 | 张亮      |      99 |   73 |      97 |
|  5 | 丽丽      |    NULL |   56 |      89 |
+----+-----------+---------+------+---------+
5 rows in set (0.00 sec)-- 查询数学成绩最大值
mysql>  select max(math) from student_grade;
+-----------+
| max(math) |
+-----------+
|        95 |
+-----------+
1 row in set (0.04 sec)-- 查询语文成绩最小值
mysql> select min(chinese) from student_grade;
+--------------+
| min(chinese) |
+--------------+
|           78 |
+--------------+
1 row in set (0.00 sec)-- 可以同时查询
mysql> select max(chinese),min(chinese) from student_grade;
+--------------+--------------+
| max(chinese) | min(chinese) |
+--------------+--------------+
|           99 |           78 |
+--------------+--------------+
1 row in set (0.00 sec)-- 使用别名
mysql> select max(chinese)数学最大值 ,min(chinese)语文最小值 from student_grade;
+-----------------+-----------------+
| 数学最大值      | 语文最小值      |
+-----------------+-----------------+
|              99 |              78 |
+-----------------+-----------------+
1 row in set (0.00 sec)

🌴 二、分组查询

🍀1.GROUP BY子句

定义

 定义:GROUP BY是SQL中用于分组聚合的核心子句,用于将查询结果按照一个或多个列的值进行分组,把具有相同列值的行归为一组。找同一组内的数据可以使用聚合函数(如COUNT、SUM、MAX、MIN)。

语法
select column1,sum(conumn2),... from table group by column1,colum3;
  • column1:分组的列名;
  • sum(column2): 没有被分组的列(需要的运算的列),如果要显示结果,需要用到聚合函数;
  • group by:分组查询的关键字;
  • column1:要分组的列名。

示例:

统计每个班级的学生数量

-- 创建学生表
mysql>  create table students(->  class_id bigint,   -- 学生所在班级->  name varchar(20)); -- 学生姓名
Query OK, 0 rows affected (0.04 sec)-- 插入
mysql>  insert into students values(1,'杨杨'),(3,'丽丽'),(1,'小美'),(2,'小帅'),(3,'王五');
Query OK, 5 rows affected (0.04 sec)
Records: 5  Duplicates: 0  Warnings: 0-- 查看学生表
mysql> select* from students;
+----------+--------+
| class_id | name   |
+----------+--------+
|        1 | 杨杨   |
|        3 | 丽丽   |
|        1 | 小美   |
|        2 | 小帅   |
|        3 | 王五   |
+----------+--------+
5 rows in set (0.00 sec)-- 分组:查看每个班级有多少学生
mysql> select class_id,count(class_id) as student_count from students group by class_id;
+----------+---------------+
| class_id | student_count |
+----------+---------------+
|        1 |             2 |
|        3 |             2 |
|        2 |             1 |
+----------+---------------+
3 rows in set (0.01 sec)-- 将其按班级编号进行升序排序
-- group by后面可以跟order by
mysql> select class_id,count(class_id) as student_count from students group by class_id order by class_id asc;
+----------+---------------+
| class_id | student_count |
+----------+---------------+
|        1 |             2 |
|        2 |             1 |
|        3 |             2 |
+----------+---------------+
3 rows in set (0.00 sec)

 🍀2.HAVING

定义

定义:对分组结果进行过滤,group by子句进行分组以后,不能使用where语句,而需要用HAVING。

-- 筛选分组后班级编号小于2的班级
mysql> select class_id,count(class_id) as student_count from students group by class_id having class_id<=2;
+----------+---------------+
| class_id | student_count |
+----------+---------------+
|        1 |             2 |
|        2 |             1 |
+----------+---------------+
2 rows in set (0.00 sec)
  • having必须和group by一起用,having要跟在group by后面; 
having与where的区别
区别wherehaving
作用对象分组前对原始数据进行筛选对分组后的结果进行筛选
使用限制不能使用聚合函数可以使用聚合函数

🌴 三、插入查询结果

插入查询结果:把一个表中的数据插入到另一个表中 

🍃语法

insert into table_name [(column1,column2,...)] 
select column1,colum2,...
from another_table
  • able_name : 被插入数据的表名;
  • another_table : 源表,即数据来源的表;
  • []:表示可写可不写,如果写了,那么colum1,colum2,...需要加上括号(),并且插入的列数量和数据类型要与被插入的列数量与数据类型相同。

示例:

将旧学生表1中的学生姓名插入到另一个表中 

-- 查看旧表学生表1找你中的信息:
mysql> select * from students;
+----------+--------+
| class_id | name   |
+----------+--------+
|        1 | 杨杨   |
|        3 | 丽丽   |
|        1 | 小美   |
|        2 | 小帅   |
|        3 | 王五   |
+----------+--------+
5 rows in set (0.02 sec)-- 创建新表
mysql> create table  new_student(-> id bigint auto_increment primary key,-> name varchar(20));
Query OK, 0 rows affected (0.09 sec)-- 将旧表中的学生名复制到新表中
mysql> insert into new_student (name) select name from students;
Query OK, 5 rows affected (0.08 sec)
Records: 5  Duplicates: 0  Warnings: 0-- 查看新表中的信息
mysql> select * from new_student;
+----+--------+
| id | name   |
+----+--------+
|  1 | 杨杨   |
|  2 | 丽丽   |
|  3 | 小美   |
|  4 | 小帅   |
|  5 | 王五   |
+----+--------+
5 rows in set (0.00 sec)

    相关文章:

  • Untiy 之如何实现一个跟随VR头显的UI
  • SVMSPro平台获取HTTP-FLV规则
  • Linux0.11系统调用:预备知识
  • docker部署deepseek
  • DDI0487--A1.7
  • 在K8S迁移节点kubelet数据存储目录
  • 对比测评:为什么AI编程工具需要 Rules 能力?
  • 五种机器学习方法深度比较与案例实现(以手写数字识别为例)
  • C#里嵌入lua脚本的例子
  • Cliosoft安装
  • 精益数据分析(31/126):电商关键指标深度解析与实战策略
  • React Native 动态切换主题
  • 【3D 地图】无人机测绘制作 3D 地图流程 ( 无人机采集数据 | 地图原始数据处理原理 | 数据处理软件 | 无人机测绘完整解决方案 )
  • Linux批量管理:Ansible自动化运维指南
  • MySQL--数据引擎详解
  • centos安装部署配置kafka
  • HCIP【VLAN技术(详解)】
  • 从架构原理到落地实践:Apache SeaTunnel×Cloudberry数据集成全解读
  • 安装WSL2,配置Ubuntu图像化界面
  • 个人开发免费好用
  • 78家公募年度业绩比拼:23家营收净利双升,十强座次微调
  • 游客曝九寨沟打网约车被出租车围堵,景区回应:当地无合规网约车
  • 西班牙葡萄牙遭遇史上最严重停电:交通瘫了,通信崩了,民众疯抢物资
  • 日本大米价格连续16周上涨,再创最高纪录
  • 恒瑞医药赴港上市获证监会备案,拟发行不超8.15亿股
  • 重新认识中国女性|婚姻,古代传统家庭再生产的根本之道