ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

SQL Server2019学习笔记--数据表的查询操作

2021-10-18 09:33:05  阅读:197  来源: 互联网

标签:Server2019 -- SNo TN 数据表 SC CNo select


--单关系表的查询
	--无条件查询
select distinct SNo from SC

	--条件查询
		--比较大小
select SNo,Score from SC where CNo='C1'

		--多重条件查询
select SNo,CNo,Score from SC 
where (CNo='C1' or CNo='C2') and Score>=85

		--确定范围
select TNo,TN,Prof from T
where Sal not between 1000 and 1500

		--确定集合
select SNo,CNo,Score from SC
where CNo not in ('C1','C2')

		--部分匹配查询
select TNo,TN from T where TN like '张%'
select TNo,TN from T where TN like '_力%'

		--空值查询
select SNo,CNo from SC where Score is null

	--常用库函数及统计汇总查询
		--SUM和AVG函数
select sum(Score) as TotalScore,avg(Score) as AvgScore
from SC where SNo='S1'

		--MAX和MIN函数
select max(Score) as MaxScore,min(Score) as MinScore,
max(Score)-min(Score) as diff from SC where SNo='S1'

		--COUNT函数
select count(distinct Dept) as DeptNum from S

	--分组查询
--查询选修两门以上课程的学生的学号和选课门数
select SNo,count(*) as C_Num from SC
group by SNo having(count(*)>=2)

	--查询结果的排序
--查询结果按学号升序排列,学号相同再按成绩降序排列
select SNo,Cno,Score from SC
where CNo in ('C2','C3','C4','C5')
order by SNo,Score desc


--多关系表的查询
	--内连接查询
--查询"刘伟"老师所讲授的课程,列出教师号、教师名和课程号
	--方法1
select T.TNO,TN,CNo from T,TC
where (T.TNO=TC.tNo) and TN='刘伟'

	--方法2
select T.TNO,TN,CNo from T inner join TC
on T.TNO=TC.tNo where TN='刘伟'

	--方法3
select R1.TNO,R2.TN,R1.CNo 
from (select TNo,CNo from TC) as R1
inner join
(select TNo,TN from T where TN='刘伟') as R2
on R1.tNo=R2.TNO

--查询每门课程的课程号、课程名和选课人数
select C.CNo,CN,count(SC.SNo) as 选课人数
from C,SC where SC.cNo=C.CNo
group by C.CNo,CN
	
	--外连接查询
--查询所有学生的学号、姓名、选课名称和成绩(没有选课同学显示为空)
select S.SNo,SN,CN,Score from S
left outer join SC on S.SNo=SC.sNo
left outer join C on C.CNo=SC.cNo
	
	--交叉连接
select * from S cross join C
	
	--自连接查询
--查询所有比"刘伟"工资高的教师姓名、工资和刘伟的工资
	--方法1
select X.TN,X.Sal AS Sal_a,Y.Sal AS Sal_b
from T as X,T as Y
where X.Sal>Y.Sal and Y.TN='刘伟'

	--方法2
select X.TN,X.Sal,Y.Sal
from T as X inner join T as Y
on X.Sal>Y.Sal and Y.TN='刘伟'

	--方法3
select R1.TN,R1.Sal,R2.Sal
from
(select TN,Sal from T) as R1
inner join
(select Sal from T where TN='刘伟') as R2
on R1.Sal>R2.Sal

--检索所有学生姓名、年龄和选课名称
	--方法1
select SN,Age,CN from S,C,SC
where S.SNo=SC.sNo and SC.cNo=C.CNo

	--方法2
select R3.SN,R3.Age,R4.CN
from 
(select SNo,SN,Age from S) as R3
inner join
(select R2.SNo,R1.CN
from
(select CNo,CN from C) as R1
inner join
(select SNo,CNo from SC) as R2
on R1.CNo=R2.cNo)
as R4
on R3.SNo=R4.sNo

标签:Server2019,--,SNo,TN,数据表,SC,CNo,select
来源: https://blog.csdn.net/qq_52652401/article/details/120820196

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有