5.1 聚合函数
sum / avg / max / min / count:把多行压成一行指标。
本讲导览
核心内容
第1节
聚合函数
1、 求和
Sum(字段名)
select sum(credit) as '学分和' from course说明:sum(字段名)函数,只能是对数值类的数据,字段类型必须是数值型。
如:select sum(teacher) as '学分和' from course 出错!
2、 求平均值
AVG(字段名)
select avg(credit) as '平均值' from course说明:AVG(字段名)函数,只能是对数值类的数据,字段类型必须是数值型。
3. 求最大值
Max(字段名)
select max(credit) as '最大值' from course说明:max(字段名)函数,字段类型可以是数值类的数据,也可以是其它类型。
Select max(teacher) as '最大值' from course4. 求最小值
Min(字段名)
select min(credit) as '最小值' from course说明:min(字段名)函数,字段类型可以是数值类的数据,也可以是其它类型。
Select min(teacher) as '最小值' from course5、 求记录行数
Count(字段名), 也可以用 count(*)格式: select count(*) from 表名 where 条件
返回符合条件的行数。如果没有where,则返回表中总行数。
说明:count(字段名),字段可以是常用任何类型。
select count(credit) as '行数' from course where credit=2
select count(*) as '总行数' from course思考题:用一条语句,在同一行内显示表course中学分credit的‘总和’、‘平均值’、‘最大值’、‘最小值’、‘记录数’
📄 展开课件原文(第 2–5 页,共 4 页)
1-2
分类汇总
1、分组(分类)
Select 字段名 from 表名 group by 字段名---- 按照字段名所在的列进行数据分类
如:select kind from course group by kind
2、 汇总(统计)
(1)计数
select kind, count(*) as '计数' from course group by kind(2)计算和
Select kind,sum(credit) as '学分和' from course group by kind(3)计算平均
select kind,avg(credit) as '学分平均' from course group by kind思考:用一条语句完成:按类别kind分类,同时显示各类别的课程数量、学分(credit)和、平均学分?
select kind,count(*) as '课程数',sum(credit) as '学分和', avg(credit) as '学分平均' from course group by kind3、汇总后的筛选
(1)非分组前的筛选,用where子句
select * from course where Credit>2(2)分组汇总后的筛选,用having代替where
select kind, SUM(credit) as '学分和' from course group by kind having sum(credit)>9📄 展开课件原文(第 6–8 页,共 3 页)
课件里的提醒 课件原文中的“说明 / 注意 / 出错”
- 说明:sum(字段名)函数,只能是对数值类的数据,字段类型必须是数值型。
- 说明:AVG(字段名)函数,只能是对数值类的数据,字段类型必须是数值型。
- 说明:max(字段名)函数,字段类型可以是数值类的数据,也可以是其它类型。
- 说明:min(字段名)函数,字段类型可以是数值类的数据,也可以是其它类型。
- 说明:count(字段名),字段可以是常用任何类型。
本讲 SQL 速览 把课件里出现的语句集中起来,方便照着敲
Sum(字段名)select sum(credit) as '学分和' from courseAVG(字段名)select avg(credit) as '平均值' from courseMax(字段名)select max(credit) as '最大值' from courseSelect max(teacher) as '最大值' from courseMin(字段名)select min(credit) as '最小值' from courseSelect min(teacher) as '最小值' from courseCount(字段名), 也可以用 count(*)select count(credit) as '行数' from course where credit=2