===== 第 1 页 ===== 第5章 SQL内置函数 1、聚合函数 2、字符函数 3、日期时间函数 4、数学函数 5、系统函数 ===== 第 2 页 ===== 第1节、聚合函数 1-1:聚合函数 1、 求和 Sum(字段名) select sum(credit) as '学分和' from course 说明:sum(字段名)函数,只能是对数值类的数据,字段类型必须是数值型。 如:select sum(teacher) as '学分和' from course 出错! ===== 第 3 页 ===== 2、 求平均值 AVG(字段名) select avg(credit) as '平均值' from course 说明:AVG(字段名)函数,只能是对数值类的数据,字段类型必须是数值型。 3. 求最大值 Max(字段名) select max(credit) as '最大值' from course 说明:max(字段名)函数,字段类型可以是数值类的数据,也可以是其它类型。 Select max(teacher) as '最大值' from course ===== 第 4 页 ===== 4. 求最小值 Min(字段名) select min(credit) as '最小值' from course 说明:min(字段名)函数,字段类型可以是数值类的数据,也可以是其它类型。 Select min(teacher) as '最小值' from course 5、 求记录行数 Count(字段名), 也可以用 count(*) 格式: select count(*) from 表名 where 条件 返回符合条件的行数。如果没有where,则返回表中总行数。 说明:count(字段名),字段可以是常用任何类型。 select count(credit) as '行数' from course where credit=2 select count(*) as '总行数' from course ===== 第 5 页 ===== 思考题:用一条语句,在同一行内显示表course中学分credit的‘总和’、‘平均值’、‘最大值’、‘最小值’、‘记录数’ ===== 第 6 页 ===== 1-2:分类汇总 1、分组(分类) Select 字段名 from 表名 group by 字段名 ---- 按照字段名所在的列进行数据分类 如:select kind from course group by kind ===== 第 7 页 ===== 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 kind ===== 第 8 页 ===== 3、汇总后的筛选 (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