SQL Server—并查询、交查询、差查询

目录

 

并查询

交查询

差查询


        student表  

                             sc表     

 

并查询

                                                             

什么是并查询?

将两个select语句查询到的结果合并

如图,将查询到的A结果集和B结果集结合在一起

代码实现:

select a.CId,a.score ,b.Sname           --找出指定学生
from sc a, student b
where a.SId =b.SId and CId = 01

union

select ' ',sum(score),'合计'               --成绩总数
from sc a, student b
where a.SId =b.SId and CId = 01

执行结果:

                  


交查询

                                                          

什么是交查询?

将两个select语句结果集结合在一起,求他们共有的部分

如图,得到结果集A和结果集B,求他们共同拥有的结果集C部分

代码实现:

select a.CId ,a.score ,b.Sname  from sc a ,student b            --查询课程为801,考试为01的学生
where a.SId =b.SId and a.CId ='01' and a.课程编号 ='801'

intersect

select top 10 a.CId ,a.score ,b.Sname  from  sc a, student b    --查询课程为801,成绩前10的学生
where a.SId =b.SId  and a.课程编号 ='801'  order by a.score desc

执行结果:

                    


差查询

差查询求的是哪部分?

去除select两个结果集不想交的地方

代码实现:

select a.CId ,a.score ,b.Sname  from sc a ,student b            --查询考试为01的学生
where a.SId =b.SId and a.CId ='01' 

except

select top 15 a.CId ,a.score ,b.Sname  from  sc a, student b    --查询课程为801,成绩前10的学生
where a.SId =b.SId  and a.课程编号 ='801'  order by a.score desc

执行结果:

                     

猜你喜欢

转载自blog.csdn.net/weixin_43319713/article/details/106084592