数据库的嵌套查询和统计查询
生活随笔
收集整理的這篇文章主要介紹了
数据库的嵌套查询和统计查询
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
①求選修了數據結構的學生學號和成績。
select s_no,score
from choice
where s_no in (select s_no from course where course_name='數據結構')
②求01001課程的成績高于張彬的學生學號和成績。
select s_no,score
from choice
where course_no='01001'
and score>(select score from choice,studentwhere choice.s_no=student.s_no and s_name='張彬')
③求其他班中比js9901班某一學生年齡小的學生姓名和年齡。
select s_name,DATEDIFF(YEAR,s_birthday,GETDATE()) s_age
from student
where s_birthday>any(select s_birthday
from student
where class_no='js9901') and class_no<>'js9901'
④求其他班中比js9901班所有學生年齡都小的學生姓名和年齡。
select s_name,DATEDIFF(YEAR,s_birthday,GETDATE()) s_age
from student
where s_birthday>all(select s_birthday from student where class_no='js9901')
and class_no<>'js9901'
⑤求選修了02001課程的學生姓名。
select s_name from student
where exists(select * from choice where course_no='02001')
⑥求沒有選修了02001課程的學生姓名。
select s_name from student
where not exists(select * from choice where course_no='02001')
⑦查詢選修了全部課程的學生的姓名。
select s_name from student
where not exists(select * from choice where s_no=student.s_no)
⑧求至少選修了學號為991101的學生所選修的全部課程的學生學號和姓名。
select s_name from student
Where s_no in (select s_no from choice c1 where not exists(select choice c2
where c2.s_no='991101'
and not exists(select choice c3 where c3.s_no=c1.s_no and c3.s_no=c2.s_no)))
① 查詢學生總人數。
select count(*) from student
② 查詢選修了課程的學生人數。
select count(distinct s_no) from choice
③ 計算01001課程的學生平均成績。
select avg(score) from choice where course_no='01001’
④ 查詢選修01001課程的學生的最高分數。
select max(score) from choice where course_no='01001'
⑤ 求學號為991101學生的總分和平均分。
select count(score),avg(score) from choice where course_no='991101'
⑥ 求各個課程號及相應的選課人數。
select course_no,count(s_no) from choice group by course_no
⑦ 查詢選修了3門以上課程的學生學號。
select s_no from choice group by s_no having count(*)>3
⑧查詢選修了3門以上且各門課程均為及格的學生的學號及其總成績,查詢結果按總成績降序列出。
select s_no,sum(score) as zongchengji from choice
where any(score)>=60
group by s_no
order by having(count(*)>3)
sum(score) desc
1. 集合查詢
在Transact-SQL中沒有直接提供集合的交操作INTERSECT和差MINUS操作,但可以使用其他方法實現。
①查詢js9902班的學生及年齡不大于19歲的學生。
select DATEDIFF(YEAR,s_birthday,GETDATE()) s_age
from student
where s_age<=19
union
select *
from student
where class_no='js9902'
②查詢選修了課程01001或者選修了01002的學生。
select s_no
from choice
where course_no='01001'
union
select s_no
from choice
where course_no='01002'
③查詢學號為991101和學號為991102的學生的學號和總分。
select s_no,sum(score)
from choice
where s_no='991101'
union
select s_no,sum(score)
from choice
where s_no='991102'
④查詢js9902班的學生與年齡不大于19歲的學生的交集。
select DATEDIFF(YEAR,s_birthday,GETDATE()) s_age
from student
where s_age<=19
intersect
select *
from student
where class_no='js9902'
⑤查詢js9902班的學生與年齡不大于19歲的學生的差集。select DATEDIFF(YEAR,s_birthday,GETDATE()) s_age
from student
where s_age<=19
except
select *
from student
where class_no='js9902'
總結
以上是生活随笔為你收集整理的数据库的嵌套查询和统计查询的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 集分宝怎么使用 集分宝的使用方法
- 下一篇: JavaScript表单