最近发现ROW_NUMBER()这个函数非常好用,用途较多,可以解决一些棘手的问题,既可满足分区的需求,也可以根据一定的顺序来排序。
语法:ROW_NUMBER() OVER(PARTITION BY col1 ORDER BY col2)
解释:根据col1 分组,在分组内部根据 col2排序,而此函数计算的值就表示每组内部排序后的顺序编号(组内连续的唯一的)
常用场景:
1、 取每一个分组的前多少名
2、删除重复数据,仅保留rownumer<xxx
// 取每一个分组的前3名
delete from tb from
(select *, ROW_NUMBER() OVER (PARTITION BY memberid order by [IsSuccess] desc) as RowNumber
from [MemberFaceIDDetectRecords] where CreatedDate > '2020.08.31'
) tb where RowNumber < 4
// 删除重读数据(RowNumber > 1)
delete from tb from
(select *, ROW_NUMBER() OVER (PARTITION BY memberid order by [IsSuccess] desc) as RowNumber
from [MemberFaceIDDetectRecords] where CreatedDate > '2020.08.31'
) tb where RowNumber > 1
// 查询重读数据(RowNumber > 1)
select * from
(select *, ROW_NUMBER() OVER (PARTITION BY memberid order by [IsSuccess] desc) as RowNumber
from [MemberFaceIDDetectRecords] where CreatedDate > '2020.08.31'
) tb where RowNumber > 1
对比SQL GROUP BY函数
每天记录一点!加油
网友评论