mysql_06_使用聚合函数查询
Posted 鑫文飘雪
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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_使用聚合函数查询的主要内容,如果未能解决你的问题,请参考以下文章
3.1.3MySQL__数据库基本建表查询,登录,sql语句,建表语句,修改表结构,增删改查,as别名,limit分页,distinct去重,聚合函数,