10. Mysql 分组或汇总查询

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,集群系列 2核4GB
简介: 10. Mysql 分组或汇总查询

Mysql 函数参考和扩展:Mysql 常用函数和基础查询Mysql 官网

Mysql 语法执行顺序如下,一定要清楚!!!运算符相关,可前往 Mysql 基础语法和执行顺序扩展。

(8) select (9) distinct (11)<columns_name list>
(1) from <left_table>
(3) <join_type> join <right_table>
(2) on <join_condition>
(4) where <where_condition>
(5) group by <group_by columns_name list>
(6) with <rollup>
(7) having <having_condition>
(10) order by <order_by columns_name list>
(12) limit <[offset,] rows>
;

1. 数据准备

这里有一张一年级一班的成绩得分表。

create table sql_test1.student_subject_scroe
(
    student_id varchar(255) comment '学生编号',
    subject    varchar(255) comment '课程名称',
    score      int comment '分数'
);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('01', 'english', 89);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('01', 'math', null);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('01', 'china', 97);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('02', 'english', 87);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('02', 'math', 53);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('02', 'china', 96);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('03', 'english', 87);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('03', 'math', 53);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('03', 'china', 96);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('04', 'english', 84);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('04', 'math', 52);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('04', 'china', 96);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('05', 'english', 74);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('05', 'math', 47);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('05', 'china', 92);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('06', 'english', 73);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('06', 'math', 40);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('06', 'china', 90);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('07', 'english', 73);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('07', 'math', 40);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('07', 'china', 90);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('08', 'english', 73);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('08', 'math', 40);
insert into sql_test1.student_subject_scroe (student_id, subject, score) values ('08', 'china', 90);

2. 汇总查询

输入的是一组数据的集合,输出的是单个值。

常用的聚合函数如下:

  • count([distinct] expr):返回expr的记录数。
  • sum(expr):返回expr的汇总值。
  • avg(expr):返回expr的平均值。
  • std(expr):返回expr的标准差。
  • max(expr):返回expr的最大值。
  • min(expr):返回expr的最小值。
  • group_concat([distinct] expr …):返回一串字符串。

统计表数据总量、学生数、有效数据数量和考试科目。

# 统计一年级一班成绩得分表,总记录数、学生人数、有效得分记录数和考试科目
select count(*)                                                      total_records,
       count(distinct student_id)                                    s_cnt,
       count(score)                                                  valid_cnt,
       group_concat(distinct subject order by subject separator '、') subjects
from sql_test1.student_subject_scroe;
+---------------+-------+-----------+------------------------+
| total_records | s_cnt | valid_cnt | subjects               |
+---------------+-------+-----------+------------------------+
|            24 |     8 |        23 | china、english、math   |
+---------------+-------+-----------+------------------------+

  • count(*):返回表中数据总量;
  • count(1):与COUNT(*)效果相同,因为它只是在每一行中都返回一个非空的值;
  • count(字段):返回字段非空值的行数;

count(*)会统计值为 NULL 的行,而count(字段)不会统计此列为 NULL 值的行。

执行效率顺序:count(*)=count(1) >count(字段)

只适用于数值类型的函数有:avg()、sum()、std();

# 查看一年级一班语文平均分,avg = sum/count
select avg(score)                              china_avg_score,
       sum(score) / count(distinct student_id) china_avg_score2,
       std(score)                              std_score
from sql_test1.student_subject_scroe
where subject = 'china';
+-----------------+------------------+--------------------+
| china_avg_score | china_avg_score2 | std_score          |
+-----------------+------------------+--------------------+
|         93.3750 |          93.3750 | 2.9553976043842236 |
+-----------------+------------------+--------------------+

3. 分组查询

SELECT中出现的非汇总聚合的字段必须声明在GROUP BY 中。

查看一年级一班各学科数据详情。

select subject,
       count(score)                                          valid_cnt,
       avg(score)                                            avg_score,
       sum(score) / count(score)                             avg_score2,
       std(score)                                            std_score,
       min(score)                                            min_score,
       max(score)                                            max_score,
       group_concat(score order by score desc separator '、') score_str
from sql_test1.student_subject_scroe
group by subject;
+---------+-----------+-----------+------------+--------------------+-----------+-----------+---------------------------------------+
| subject | valid_cnt | avg_score | avg_score2 | std_score          | min_score | max_score | score_str                             |
+---------+-----------+-----------+------------+--------------------+-----------+-----------+---------------------------------------+
| china   |         8 |   93.3750 |    93.3750 | 2.9553976043842236 |        90 |        97 | 97、96、96、96、92、90、90、90        |
| english |         8 |   80.0000 |    80.0000 | 6.8738635424337655 |        73 |        89 | 89、87、87、84、74、73、73、73        |
| math    |         7 |   46.4286 |    46.4286 |  5.876275371772324 |        40 |        53 | 53、53、52、47、40、40、40            |
+---------+-----------+-----------+------------+--------------------+-----------+-----------+---------------------------------------+

查看一年级一班学科平均分低于60的学科数据详情

select subject,
       count(score)                                          valid_cnt,
       avg(score)                                            avg_score,
       sum(score) / count(score)                             avg_score2,
       std(score)                                            std_score,
       min(score)                                            min_score,
       max(score)                                            max_score,
       group_concat(score order by score desc separator '、') score_str
from sql_test1.student_subject_scroe
where score is not null
group by subject
having avg(score) < 60;
+---------+-----------+-----------+------------+-------------------+-----------+-----------+----------------------------------+
| subject | valid_cnt | avg_score | avg_score2 | std_score         | min_score | max_score | score_str                        |
+---------+-----------+-----------+------------+-------------------+-----------+-----------+----------------------------------+
| math    |         7 |   46.4286 |    46.4286 | 5.876275371772324 |        40 |        53 | 53、53、52、47、40、40、40       |
+---------+-----------+-----------+------------+-------------------+-----------+-----------+----------------------------------+

WHEREHAVING的区别:

  • WHERE用于在执行查询之前对行进行筛选,而HAVING用于对查询结果进行分组后的筛选。
  • WHERE可以应用于单个表或多个表的连接查询,而HAVING必须与GROUP BY一起使用。
  • WHERE可以使用各种条件表达式进行筛选,而HAVING可以使用聚合函数和条件表达式对分组后的结果进行筛选。

相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
3月前
|
缓存 关系型数据库 MySQL
MySQL索引策略与查询性能调优实战
在实际应用中,需要根据具体的业务需求和查询模式,综合运用索引策略和查询性能调优方法,不断地测试和优化,以提高MySQL数据库的查询性能。
317 66
|
2月前
|
SQL 关系型数据库 MySQL
【MySQL基础篇】多表查询(隐式/显式内连接、左/右外连接、自连接查询、联合查询、标量/列/行/表子查询)
本文详细介绍了MySQL中的多表查询,包括多表关系、隐式/显式内连接、左/右外连接、自连接查询、联合查询、标量/列/行/表子查询及其实现方式,一文全面读懂多表联查!
【MySQL基础篇】多表查询(隐式/显式内连接、左/右外连接、自连接查询、联合查询、标量/列/行/表子查询)
|
29天前
|
缓存 关系型数据库 MySQL
【深入了解MySQL】优化查询性能与数据库设计的深度总结
本文详细介绍了MySQL查询优化和数据库设计技巧,涵盖基础优化、高级技巧及性能监控。
239 0
|
2月前
|
存储 Oracle 关系型数据库
索引在手,查询无忧:MySQL索引简介
MySQL 是一款广泛使用的关系型数据库管理系统,在2024年5月的DB-Engines排名中得分1084,仅次于Oracle。本文介绍MySQL索引的工作原理和类型,包括B+Tree、Hash、Full-text索引,以及主键、唯一、普通索引等,帮助开发者优化查询性能。索引类似于图书馆的分类系统,能快速定位数据行,极大提高检索效率。
78 8
|
2月前
|
SQL 关系型数据库 MySQL
MySQL 窗口函数详解:分析性查询的强大工具
MySQL 窗口函数从 8.0 版本开始支持,提供了一种灵活的方式处理 SQL 查询中的数据。无需分组即可对行集进行分析,常用于计算排名、累计和、移动平均值等。基本语法包括 `function_name([arguments]) OVER ([PARTITION BY columns] [ORDER BY columns] [frame_clause])`,常见函数有 `ROW_NUMBER()`, `RANK()`, `DENSE_RANK()`, `SUM()`, `AVG()` 等。窗口框架定义了计算聚合值时应包含的行。适用于复杂数据操作和分析报告。
126 11
|
2月前
|
存储 关系型数据库 MySQL
mysql怎么查询longblob类型数据的大小
通过本文的介绍,希望您能深入理解如何查询MySQL中 `LONG BLOB`类型数据的大小,并结合优化技术提升查询性能,以满足实际业务需求。
175 6
|
3月前
|
SQL 前端开发 关系型数据库
SpringBoot使用mysql查询昨天、今天、过去一周、过去半年、过去一年数据
SpringBoot使用mysql查询昨天、今天、过去一周、过去半年、过去一年数据
99 9
|
3月前
|
缓存 监控 关系型数据库
如何优化MySQL查询速度?
如何优化MySQL查询速度?【10月更文挑战第31天】
226 3
|
3月前
|
SQL NoSQL 关系型数据库
2024Mysql And Redis基础与进阶操作系列(5)作者——LJS[含MySQL DQL基本查询:select;简单、排序、分组、聚合、分组、分页等详解步骤及常见报错问题所对应的解决方法]
MySQL DQL基本查询:select;简单、排序、分组、聚合、分组、分页、INSERT INTO SELECT / FROM查询结合精例等详解步骤及常见报错问题所对应的解决方法
|
3月前
|
监控 关系型数据库 MySQL
数据库优化:MySQL索引策略与查询性能调优实战
【10月更文挑战第27天】本文深入探讨了MySQL的索引策略和查询性能调优技巧。通过介绍B-Tree索引、哈希索引和全文索引等不同类型,以及如何创建和维护索引,结合实战案例分析查询执行计划,帮助读者掌握提升查询性能的方法。定期优化索引和调整查询语句是提高数据库性能的关键。
586 1

推荐镜像

更多