首页 > 代码库 > mysql_06_使用聚合函数查询
mysql_06_使用聚合函数查询
#使用数据库
USE db_student;
#创建表
create table `t_grade` (
`id` int PRIMARY KEY auto_increment NOT NULL,
`stuName` varchar (60),
`course` varchar (60),
`score` int
);
#插入数据
insert into `t_grade` (`id`, `stuName`, `course`, `score`) values(‘1‘,‘张三‘,‘语文‘,‘91‘);
insert into `t_grade` (`id`, `stuName`, `course`, `score`) values(‘2‘,‘张三‘,‘数学‘,‘90‘);
insert into `t_grade` (`id`, `stuName`, `course`, `score`) values(‘3‘,‘张三‘,‘英语‘,‘87‘);
insert into `t_grade` (`id`, `stuName`, `course`, `score`) values(‘4‘,‘李四‘,‘语文‘,‘79‘);
insert into `t_grade` (`id`, `stuName`, `course`, `score`) values(‘5‘,‘李四‘,‘数学‘,‘95‘);
insert into `t_grade` (`id`, `stuName`, `course`, `score`) values(‘6‘,‘李四‘,‘英语‘,‘80‘);
insert into `t_grade` (`id`, `stuName`, `course`, `score`) values(‘7‘,‘王五‘,‘语文‘,‘77‘);
insert into `t_grade` (`id`, `stuName`, `course`, `score`) values(‘8‘,‘王五‘,‘数学‘,‘81‘);
insert into `t_grade` (`id`, `stuName`, `course`, `score`) values(‘9‘,‘王五‘,‘英语‘,‘89‘);
#第五章:单表操作
#第二节:使用聚合函数查询
#5.1:COUNT()函数
SELECT COUNT(*) FROM t_grade;#统计记录的条数
SELECT COUNT(*) AS total FROM t_grade;#添加别名
SELECT stuName,COUNT(course) AS "科目数" FROM t_grade GROUP BY stuName,course;
SELECT stuName,GROUP_CONCAT(course) AS "科目" FROM t_grade GROUP BY stuName;
#5.2:sum()函数
SELECT stuName,GROUP_CONCAT(course) AS "科目",SUM(score) AS "总分" FROM t_grade WHERE stuName="张三";
SELECT stuName,GROUP_CONCAT(course) AS "科目",SUM(score) AS "总分" FROM t_grade GROUP BY stuName;
#5.3:avg()函数
SELECT stuName,GROUP_CONCAT(course) AS "科目",AVG(score) AS "平均分" FROM t_grade WHERE stuName="李四";
SELECT stuName,GROUP_CONCAT(course) AS "科目",AVG(score) AS "平均分" FROM t_grade GROUP BY stuName;
#5.4:max()函数
SELECT stuName,MAX(score) AS "分数" FROM t_grade WHERE stuName="王五";
SELECT stuName,MAX(score) AS "最高分" FROM t_grade GROUP BY stuName;
#5.5:min()函数
SELECT stuName,MIN(score) AS "最低分" FROM t_grade WHERE stuName="李四";
SELECT stuName,MIN(score) AS "最低分" FROM t_grade GROUP BY stuName;
mysql_06_使用聚合函数查询