sql server单表查询

sql server单表查询


1.查询全体学生的姓名及出生年份

select sname,2019-sage birth from student

2.查询全体学生的姓名,出生年份,和所在的院系,要求用大写字母表示系名

select sname,2019-sage birth,upper(sdept)sdept from student
#小写用lower

3.查询所有年龄在20岁以下的学生姓名及其年龄

select sname,sage from student where sage<20

4. 查询考试成绩不及格的学生的学号

select sno from sc where grade<100
#注:其中有很多重复的

select distinct sno from sc where grade<100
注:去除重复

5.查询年龄在20-23之间的学生的姓名

select sname from student where sage between 20 and 23

6.查询sdept是’cs’,‘ma’,'is’的学生的姓名
  • 方法1:

select sname from student where sdept in(‘cs’,‘ma’,‘is’)

  • 方法2:

select sname from student
where sdept=‘cs’ or sdept=‘ma’ or sdept=‘is’

7. 查询sdept不是’cs’,‘ma’,'is’的学生的姓名

select sname from student where sdept not in(‘cs’,‘ma’,‘is’)

8. 查询所有姓刘的学生的学号

select sno from student where sname like ‘刘%’
#%代表任意长度

9.查询姓“王敏”学生的姓名,且全名为两个字

select sname from student where sname like ‘_敏’

#_代表单个字符

10. 查询所有不姓刘的学生的姓名

select sname from student where sname not like ‘刘%’

11. 查询课程为db_design的课程号

select cno from course where cname like ‘db_design’ escape ‘’
#escape ''表示紧跟在 ''后面的字符‘_’不在具有通配意义

12. 查询缺少成绩的学生的学号和相应的课程号

select sno,cno from sc where grade is null

13. 查询有成绩的学生的学号和相应的课程号

select sno,cno from sc where grade is not null

14. 查询cs中年龄<20学生的姓名

select sname from student where sdept ='cs’and sage <20

oreder by 子句

15. 查询选修了3号课程的学生的学号及其成绩,查询结果按分数降序排列

select sno,grade from sc where cno=‘3’ order by grade desc

16. 查询全体学生情况,查询结果按所在系的系号升序排列,同一系中的学生按年龄降序排列

select * from student order by sdept asc ,sage desc

聚集函数

17. 查询学生总人数

select count(*) from student

18. 查询选修了课程的人数

select count(distinct sno) from sc

19. 计算选修了1号课程的学生平均成绩

select avg(grade) from sc where cno=‘1’

20. 计算选修了1号课程的学生的最高分数

select max(grade) from sc where cno=‘1’

21. 查询学生 201215012 选修课程的总学分数

select sum(ccredit) from course ,sc
where sno=‘201215012’
and sc.cno=course.cno

group by 子句

22. 求各个课程号及相应的选课人数

select cno,count(sno) from sc group by cno

23. 查询选修了三门以上课程的学生学号

select sno from sc group by sno having count(*)>=3

24. 查询平均成绩>=60的学生学号和平均成绩

select sno, avg (grade) from sc group by sno having avg (grade) >= 60

你可能感兴趣的:(SQL,SERVER,单表查询)