MySQL常用聚合函数【 学习记录 】

前言

整理复习MySQL数据库,记录学习,涵盖较全!


1. 聚合函数

准备:t_grade表,代码如下

-- ----------------------------
-- Table structure for t_grade
-- ----------------------------
DROP TABLE IF EXISTS `t_grade`;
CREATE TABLE `t_grade` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `stuName` varchar(60) DEFAULT NULL,
  `course` varchar(60) DEFAULT NULL,
  `score` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of t_grade
-- ----------------------------
INSERT INTO `t_grade` VALUES ('1', '张三', '语文', '91');
INSERT INTO `t_grade` VALUES ('2', '张三', '数学', '90');
INSERT INTO `t_grade` VALUES ('3', '张三', '英语', '87');
INSERT INTO `t_grade` VALUES ('4', '李四', '语文', '79');
INSERT INTO `t_grade` VALUES ('5', '李四', '数学', '95');
INSERT INTO `t_grade` VALUES ('6', '李四', '英语', '80');
INSERT INTO `t_grade` VALUES ('7', '王五', '语文', '77');
INSERT INTO `t_grade` VALUES ('8', '王五', '数学', '81');
INSERT INTO `t_grade` VALUES ('9', '王五', '英语', '89');

在这里插入图片描述

1.1 COUNT 函数

1. COUNT()函数用来统计记录的条数。

-- 一般写法
select count(*) from t_grade;
-- 或者加个别名
select count(*) "成绩表总记录数" from t_grade;

在这里插入图片描述

2. 与 GROUP BY 关键字一起使用;

-- 根据学生姓名分组,显示学生姓名和每个学生上了几门课
select stuName,COUNT(course) from t_grade group by stuName;

在这里插入图片描述

1.2 SUM 求和函数

1. 基础用法

-- 查询张三的课程总成绩
select stuName,sum(score) from t_grade where stuName = "张三";

在这里插入图片描述

-- 查询张三的总成绩和课程
select stuName,group_concat(course).sum(score) from t_grade where stuName = "张三";

在这里插入图片描述

扫描二维码关注公众号,回复: 15026559 查看本文章

2. 与GROUP BY关键字结合

-- 查询学生的课程和课程总成绩
select stuName,group_concat(course),sum(score) from t_grade group by stuName;

在这里插入图片描述

1.3 AVG 函数

1. 基础用法

-- 查询张三的课程平均成绩
select stuName,avg(score) from t_grade where stuName = "张三";

在这里插入图片描述

2. 与GROUP BY关键字结合

-- 根据学生姓名分组,显示平均分
select stuName,avg(score) from t_grade group by stuName;

在这里插入图片描述

1.4 MAX 函数

1. 基础用法

-- 查询张三考的最高分
select max(score) from t_grade where stuName = "张三";

在这里插入图片描述

-- 将张三的最高分作为子查询返回的结果当做条件,
-- 查询张三最高分对应的的所有信息
select * from t_grade where stuName = "张三" and score = 
(select max(score) from t_grade where stuName = "张三");

在这里插入图片描述

2. 与GROUP BY关键字结合

-- 查询每个学生的课程最高分
select stuName,max(score) from t_grade group by stuName;

在这里插入图片描述

1.5 MIN 函数

1. 基础用法

-- 查询张三课程的最低分
select min(score) from t_grade where stuName = "张三";

在这里插入图片描述

2. 与GROUP BY关键字结合

-- 查询每个人课程的最低分
select stuName,min(score) from t_grade group by stuName;

在这里插入图片描述


结束

以上为全部内容,欢迎讨论,记录学习!

猜你喜欢

转载自blog.csdn.net/m0_59420288/article/details/128783578
今日推荐