码迷,mamicode.com
首页 > 数据库 > 详细

mysql_06_使用聚合函数查询

时间:2017-07-27 01:02:49      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:插入数据   插入   avg   5.4   table   where   min()   null   聚合   

#使用数据库
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_使用聚合函数查询

标签:插入数据   插入   avg   5.4   table   where   min()   null   聚合   

原文地址:http://www.cnblogs.com/xinwenpiaoxue/p/7242505.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!