加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

(数据库SQL)表的的分组查询和统计查询

(2011-11-04 10:17:15)
标签:

杂谈

分类: 自己写哒

一、使用聚集函数

1 查询学生总人数;
select count(*)coun
from student;

2 查询选修了课程的学生总数;
select count(distinct sno)num
from sc;

3 查询所有课程的总学分数和平均学分数,以及最高学分和最低学分;
select sum(grade)su,avg(grade)av,max(grade)ma,min(grade)mi
from sc;

4 计算1号课程的学生的平均成绩, 最高分和最低分;
select avg(grade)av,max(grade)ma,min(grade)mi
from sc
where cno=1;
5 查询’信息系’(IS)学生”数据结构”课程的平均成绩;
select avg(grade) av
from sc,student,course
where student.sno=sc.sno and sc.cno=course.cno and sdept='IS' and cname='数据结构';

6 查询每个学生的课程成绩最高的成绩信息(sno,cno,grade) ;
select sno,cno,grade
from sc scx
where grade=(select max(grade)
             from sc scy
             where scy.sno=scx.sno)

 

7 求成绩低于该门课程平均成绩的学生的成绩信息(sno,cno,grade)。

select sno,cno,grade
from sc scx
where grade<(select avg(grade)
             from sc scy
             where scy.cno=scx.cno);

二、 分组查询

1 查询各系的学生的人数并按人数从多到少排序;
select sdept,count(sno)num
from student
group by sdept
order by count(sno)DESC;

2 查询各系的男女生学生总数, 并按系别,升序排列, 女生排在前;
select sdept,ssex,count(ssex)num
from student
group by sdept,ssex
order by sdept ASC,ssex DESC;
 

3 查询选修了3门课程已上的学生的学号和姓名;
select sno,sname
from student
where sno in( select sno
              from sc
              group by sno
              having count(cno)>3);

4 查询每个学生所选课程的平均成绩, 最高分, 最低分,和选课门数;
select sno,avg(grade)av,max(grade)ma,min(grade)mi,count(*)num
from sc
group by sno ;

5 查询至少选修了2门课程的学生的平均成绩;
select sno, avg(grade) av
from sc
group by sno
having count(*)>=2;
6 查询平均分超过80分的学生的学号和平均分;
select sno ,avg(grade) av
from sc
group by sno
having avg(grade)>80;

7 查询”信息系”(IS)中选修了5门课程以上的学生的学号。

select sno
from sc
group by sno
having count(*)>5;
三、集合查询

1 查询数学系和信息系的学生的信息;
select *
from student
where sdept in('MA','IS');

2 查询选修了1号课程或2号课程的学生的学号。
select sno
from sc
where cno in(1,2);

 

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有