MySQL之单表查询

单表查询(组函数)

常用组函数有 :
count() : 总条数
max(字段名) : 最大值
min(字段名) : 最小值
avg(字段名) : 平均值
sum(字段名) : 总和
示例数据
create table student (
id int ,
name varchar(20),
teacher_id int,
score decimal(18,2) ,
primary key (id)
);
create table teacher(
id int ,
name varchar(20),
primary key (id)
);
insert into teacher (id,name)values(1,‘张老师’);
insert into teacher (id,name)values(2,‘王老师’);
insert into student (id,name,teacher_id,score)values(1,‘张三’,1,90);
insert into student (id,name,teacher_id,score)values(2,‘李四’,2,88.9);
insert into student (id,name,teacher_id,score)values(3,‘王五’,1,45.7);
insert into student (id,name,teacher_id,score)values(4,‘赵六’,1,84);
insert into student (id,name,teacher_id,score)values(5,‘小明’,2,92.5);
insert into student (id,name,teacher_id,score)values(6,‘小红’,2,47);
语法 :
select count(
),max(字段名),min(字段名)… from 表名 group by 字段名;
如 : 查看学生表共有多少学生
select count() from student;
如 : 查看学生表中分数大于90分的有多少学生
select count(
) from student where score > 90;
Group by
如 : 查询每个老师分别带了多少学生(显示老师id即可)
select teacher_id, count() as stu_count from student group by teacher_id;
如 : 查询每个老师带的学生中的最高分数
select teacher_id, count(
) as stu_count,max(score) as stu_max_score from student group by teacher_id;
如 : 查询每个老师所带学生的总成绩与平均分
select teacher_id, sum(score) as sum,avg(score) as avg from student group by teacher_id;
Having
刚才我们使用group by 和 组函数,可以对数据进行分组查询,并且也可以查询到平均值等数据
但是有时候我们也需要做一些判断,比如求出平均值了,我只想要平均值 大于60分的平均分数,这时候用where就不行了
select teacher_id, avg(score) as avg from student where avg > 60 group by teacher_id;
这个时候就需要使用having进行过滤
select teacher_id, avg(score) as avg from student group by teacher_id having avg > 60;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值