SQL over的作用及用法
sql over的作用及用法 RANK ( ) OVER ( [query_partition_clause] order_by_clause ) DENSE_RANK ( ) OVER ( [query_partition_clause] order_by_clause ) 可实现按指定的字段分组排序,对于相同分组字段的结果集进行排序, 其中PARTITION BY 为分组字段,ORDER BY 指定排序字段 over不能单独使用,要和分析函数:rank(),dense_rank(),row_number()等一起使用。 其参数:over(partition by columnname1 order by columnname2) 含义:按columname1指定的字段进行分组排序,或者说按字段columnname1的值进行分组排序。 例如:employees表中,有两个部门的记录:department_id =10和20 select department_id,rank() over(partition by department_id order by salary) from employees就是指在部门10中进行薪水的排名,在部门20中进行薪水排名。如果是partition by org_id,则是在整个公司内进行排名。
SELECT *, Row_Number() OVER (partition by deptid ORDER BY salary desc) rank FROM employee
select ROW_NUMBER() over(order by id1) odid,* from #t1 select ROW_NUMBER() over(partition by id1 order by id1) odid,* from #t1 select ROW_NUMBER() over(partition by id1,id2 order by id1) odid,* from #t1 select ROW_NUMBER() over(partition by id1,id2,id3 order by id1) odid,* from #t1
--ROW_NUMBER 还可以用查重复数据,1代表的是出现的次数,保留id2最大的,并把其他的删除掉. delete a from (select ROW_NUMBER()over(partition by id1 order by id2 desc) orderid from #t1 ) a where a.orderid>1
SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY id asc) AS rownum, id FROM company ) AS D WHERE rownum BETWEEN (@pageIndex-1)*@pageSize+1 AND @pageIndex*@pageSize ORDER BY id asc
with cte as( select dense_rank() over(order by Score desc) rank,* from @t ) select * from cte where rank < 6