【数据库】常用语法
select from where order by > >= < <= != and or not
模糊匹配 like % _
空值 null
为空 is null
在集合里 in (集合)
存在 in
排序 order by asc desc
取前n个 top(n)
随机抽取 rand(), newid()
集函数 计数 count() distinct -剔除重复
求和 sum(数值列) avg() max min
分组 group by 列
筛选 having
已知:
Student(Sno,Sname,Ssex,Sage,Sdept)
Course(Cno,Cname,Ccredit,Cpno)
SC(Sno,Cno,Grade)
- 查询挂科超过2门的同学的姓名
select Sname from Student where Sno in (
select Sno from SC where Grade <60 group by Sno having count(*) >=2)
- 查询年龄最大的学生
select top 2 * from Student order by Sage
- 随机挑选10名学生 newid()
select top 10 * from Student order by newid()
- 挑选成绩排名前三的同学
select top 3 * from SC order by Grade desc
- 查询成绩全部优秀同学 (逆否命题:不存在成绩不优秀的选课,同时这个同学一定选课)
select * from Student where not Sno in(
select Sno from SC where Grade < 90) and Sno in(
select Sno from SC where Grade >=90) and not Sno in (
select Sno from SC where Grade is null)
- 模糊匹配 like %表示任意字符 _单个字符 escape 转义符
select * from Student where ssex ='女' and Sname like '刘%'
- IS或CS系的同学
in 集合
select * from Student where Sdept in('IS','CS')
- 统计每个系的女生人数并且查询女生数大于2的系名称
select count(*), Sdept from Student
where Ssex = '女'
group by Sdept
having count(*) >=2
- 年龄降序排列的前50%的同学
select top (select count(*) * 50/100 from Student) * from Student
order by Sage desc
- 查询姓刘并且所有课程成绩均90分以上的女同学
select * from Student where not Sno in(
select Sno from SC where Grade < 90) and Sno in(
select Sno from SC where Grade >=90) and not Sno in (
select Sno from SC where Grade is null)
and ssex ='女' and Sname like '刘%'
- 查询 保研的同学占比一半 英语成绩大于85,平均成绩前 15%同学 (4学分以上课程不挂科)
select * from Student where Sno in(
select top (select count(*) * 50/100 from Student)
Sno from SC where Sno in( -- 英语85分以上
select Sno from SC where Grade >=85 and Cno in (select Cno from Course
where Cname = '英语')) and not Sno in (select Sno from SC where Grade <60
and Cno in (select Cno from Course where Ccredit >=4))
group by Sno order by avg(Grade) desc
)