一、函数学习
1、ROW_NUMBER() OVER()函数
语法格式:row_number() over(partition by 分组列 order by 排序列 desc)
注意;在使用 row_number() over()函数时候,over()里头的分组以及排序的执行晚于 where 、group by、 order by 的执行。
①表数据
1 create table TEST_ROW_NUMBER_OVER( 2 id varchar(10) not null, 3 name varchar(10) null, 4 age varchar(10) null, 5 salary int null 6 ); 7 select * from TEST_ROW_NUMBER_OVER t; 8 9 insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(1,'a',10,8000); 10 insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(1,'a2',11,6500); 11 insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(2,'b',12,13000); 12 insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(2,'b2',13,4500); 13 insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(3,'c',14,3000); 14 insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(3,'c2',15,20000); 15 insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(4,'d',16,30000); 16 insert into TEST_ROW_NUMBER_OVER(id,name,age,salary) values(5,'d2',17,1800);View Code
②进行一次排序,无分组
格式:row_number() over(order by 字段 desc)
select id,name,age,salary,row_number() over(order by salary desc) rn from TEST_ROW_NUMBER_OVER
③根据id分组排序
格式 row_number()over(partition by 字段1 order by 字段2 desc) 根据字段1进行分组,再根据字段2进行组内排序
select id,`name`,age,salary,row_number()over(partition by id order by salary desc) rn from TEST_ROW_NUMBER_OVER t;
④练习题
有这么一张表student,存在多个相同数据的项,因此请删除no、name、score都不相同的项。
第一步使用开窗函数筛选出以no、name、score为分组的项
select id,`no`,`name`,score,row_number()over(partition by `no`,`name`,score)as num from student
第二部通过join连接表进行删除多余相同的项
delete s from student s join (select id,`no`,`name`,score,row_number()over(partition by `no`,`name`,score)as num from student) a
on s.id = a.id where num != 1
执行完delete后在查询整个student表