SQL数据库,重复数据选其中几条,联表查询去重||联表查询不包含数据

表中有很多重复数据,需要它和另外一个表通过身份证号联表查询,但是因为该表重复数据多,查出数据过多

复制代码

create table Student  --学生成绩表
(
 id int,  --主键
 Grade int, --班级
 Score int --分数
)
go

insert into Student values(1,1,88)
insert into Student values(2,1,66)
insert into Student values(3,1,75)
insert into Student values(4,2,30)
insert into Student values(5,2,70)
insert into Student values(6,2,80)
insert into Student values(7,2,60)
insert into Student values(8,3,90)
insert into Student values(9,3,70)
insert into Student values(10,3,80)
insert into Student values(11,3,80)

复制代码

一、分区函数Partition By的与row_number()的用法

1、不分班按学生成绩排名

select *,row_number() over(order by Score desc) as Sequence from Student

执行结果:

2、分班后按学生成绩排名

select *,row_number() over(partition by Grade order by Score desc) as Sequence from Student

执行结果:

3、获取每个班的前1(几)名

select * from
(
select *,row_number() over(partition by Grade order by Score desc) as Sequence from Student
)T where T.Sequence<=1

执行结果:

---------------------------------------------------------------我是分割线---------------------------------------------------------------------------

不包含

//通过身份证号对比,找到春季雨露计划中的贫困登记学生,共292条
CREATE VIEW view3 AS
SELECT * FROM [宜城市].[dbo].[春季雨露计划] as a,[宜城市].[dbo].贫困户信息表 as b where a.学生身份证号=b.证件号码

//春季雨露计划中不存在(贫困登记学生)
select * from [宜城市].[dbo].[春季雨露计划] where not exists(select view3.学生身份证号 from view3 where view3.学生身份证号=[宜城市].[dbo].[春季雨露计划].学生身份证号)

猜你喜欢

转载自blog.csdn.net/qq_21036939/article/details/85764753
今日推荐