专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > Sql Server

分组查询之小试锋芒

发布时间:2010-05-20 14:01:29 文章来源:www.iduyao.cn 采编人员:星星草
分组查询之牛刀小试!

学习数据库那么长时间了,对与分组查询也算是有点了解了,带大家一起来回顾下我们的分组查询>>>

在分组查询的应用中要充分的利用前面的所学,

例如充分的利用字符串函数,日期函数,数学函数,系统函数,以及我们的聚合函数.

那么接下来就具体的来看看吧!

现有一个这样的数据库

具体表中有其关键列

接下来带大家来实现第一个小功能:

1.查询每个年级的总学时数,并按照升序排列

select * from Subject
select gradeid, sum(classhour) as 总学时数
from Subject
group by GradeId
order by sum(classhour)

2.查询每个参加考试的学员的平均分

select * from Result
select studentno as 学员编号,AVG(studentresult) as 平均分
from Result 
group by studentno

3.查每门课程的平均分,并按照降序排列

select * from Result
select subjectid as 课程编号,AVG(studentResult) as 平均分
from Result
group by SubjectId
order by 平均分 desc 

4.查询每个学生参加的所有考试的总分,并按照降序排列

select * from Result
select studentno,sum(StudentResult) as 学员分数
from Result
group by studentno
order by 学员分数 desc 

 

ok,在见证了这么easy的小知识后,小编也不再藏着掖着了,接下来看看我们的杀手锏吧!

在这里简单提一下在写查询语句时需要注意的事项:

如果语句中有group by关键字,那么select后只能跟group by后出现的列,或者是聚合函数

1.查询每学期学时数超过50的课程数

select * from Subject

select GradeId,COUNT(SubjectId) as 总时数
 from Subject
where ClassHour>50
group by GradeId

2.查询每学期学生的平均年龄

select * from Student
select gradeid,AVG(DATEDIFF(YY,birthday,GETDATE())) as 平均年龄
from Student
group by gradeid

3.查询北京地区的每学期人数

select * from Student
select gradeid,COUNT(1) as 总人数
from student
where address like '%北京%'
group by Gradeid

4.查询参加考试的学生中,平均分及格的学生记录(学号,平均分),按照降序排列

select * from Result

select studentno,AVG(StudentResult) as 平均分
from Result
group by StudentNo
having AVG(StudentResult)>=60
order by 平均分 desc

5.查询考试时间为2009-9-9课程的及格平均分

select subjectid,AVG(studentresult) as 平均分
from Result
where ExamDate>='2009-9-9' and  ExamDate<'2009-9-10'
group by SubjectId
having AVG(StudentResult)>=60

6.统计至少有一次不及格的学生学号和次数

select studentno,COUNT(1) as  次数
from Result
where StudentResult<60
group by StudentNo

 

 

 

having字句的位置不要记错了  

既然提到了位置,在这里又不得不说一下在语句的执行过程中字句的执行是有先后顺序的:

 

3楼天尽头的那片海
好,爱你哟!
2楼微冷的风
Nice,,,,,,,,,,,,,,, 大班生到此一观!
1楼葉子。
每一篇文章都让我看出你的进步,也让我学到不少东东,我期待你的下篇文章.
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: