常用SQL语句
一 查询语句
-1 查询所有记录从student
Select * from student
-2. 查询部s_no,s_name 段从student 中。
select s_name,s_no from student
-3 查询并采用别名选择s_name,=( 姓名) ,s_no (学号)从student
select 学号=s_no, 姓名=s_name from student
或者select s_no as 学号,s_name as 姓名 from student
-4 查询年龄在23 岁以上的所有学生的姓名和年龄并按照年龄倒排序
select s_name,s_age from student where s_age>23 order by s_age desc
-5 查询姓张的所有学生
select *from student where s_name like'张%'
-6 查询所有年龄在23-25 之间,并且是男学生,还要姓张,只返回前一条记录, 并按照年龄和所在系倒排序
。
select top 1*from student where s_name like'%张%' and s_sex='男' and s_age between 23 and
25 order by s_age desc, s_dept asc
-7 查询既不是交通工程系,也不是土木的学生的姓名和年龄及所在系。
select s_name,s_age ,s_dept from student where s_dept not in('交通工程系','土木')
-8 查询所有学生中不姓张的学生
select * from student where s_name not like '张%'
-9 从学生表中查询学号的最后一位不在6-9 范围内的学生情况
select * from student where substring(s_no,8,1) not like'[6-9]'
-10 查询成绩表中成绩是空的学生的情况
select * from sc where c_grade=null
-11 查询学生总人数
select count(*) as 总人数 from student
-12 查询选修了课程的学生人数
select count(*) as 总人数 from sc
-13 计算所有男生的成绩之和
select sum(c_grade)from sc sc ,student where s_sex='男'and student.s_no=sc.s_no
-14 查询课程号为c002 的学生平均成绩
select avg(c_grade)from sc where c_no='c002'
-15 查询选修了课程的学生
select count(distinct s_no) from sc
-16 查询选修了r001 课程的学生最高分和最低分。
select max(c_grade),min(c_grade) from sc where c_no='r001'
-17 统计每门课程的选课人数,并列出课程号和人数
select c_no ,count(*)from sc group by c_no
-18 查询每名学生的选课门数和平均成绩
select s_no ,count(*),avg(c_grade)from sc group by s_no
-19 查询修了3 门以上课程的学生学号
select s_no ,count(*)from sc group by s_no having count(*)>=3
-20 查询修课门数大于等于3 的学生平均成绩和选课门数
select s_no ,avg(c_grade),count(*)from sc group by s_no having count(*)>=3
-21 查询每个学生的修课情况
select * from student ,sc where student.s_no=sc.s_no(两个表中的学号字段均列出)
-22 查询计算机学生的修课情,要求列出学生的名字、所修课程号和成绩
select s_name,c_no ,c_grade from student a ,sc b where s_dept='计算机'and a.s_no=b.s_no
-23 查询选修了大学语文课程的学生修课成绩,要求列出学生的名字,所修的课程名和成绩
elect s_name,c_name ,c_grade from student a ,sc b,course c where c_name='大学语文'and
a.s_no=b.s_no and b.c_no=c.c_no
-24 将学生的姓名,修课的课程名和成绩存放在永久表s_c_g 中
select a.s_name,c.c_name ,b.c_grade into s_c_g from student a ,sc b,course c
-25 查询修了roo1 课程的切成绩成绩高于此课程的平均成绩的学生的学号和成绩
select s_no ,c_grade from sc where c_no='r001' and c_grade>(select avg(c_grade) from sc where
c_no='r001')
-26 查询与李四在同一个系学习的学生
select s_name from student where s_dept=(select s_dept from student where s_name='李四')and
s_name<>'李四'
-27 查询全体学生的姓名和出生年份
select s_name,nf=datepart(yyyy,getdate())-s_age from student
二 更新语句
-1 将新生记录(20010694 、陈东、男、交通工程系、22 岁)插入到表student 中
insert into student(s_no,s_name,s_sex,s_dept,s_age)values('20010694','陈东','男','交通工程系
','22')
-2 在 sc 表中插入一条新记录,成绩暂缺
insert into sc(s_no,c_no,c_grade)values('20010694','j002',null)
-3 将所有学生功的年龄加一
update student set s_age=s_age+1
-4 删除所有学生的选课记录
delete from sc
-5 删除所有成绩不及格学生的成绩记录
Delete from sc where c_grade<60
-6 删除计算机不及格学生的修课记录
delete from sc where c_grade<60 and s_no in(select s_no from student where s_dept='计算机')