MYSQL-实现分组排序 对比 ORACLE 和SQLserver用 row_number() over(partition by ) 分组排序功能

以下是个人笔记:

本文是为了理解 row_number() over(partition by )  和实现各种数据库的分组排序功能

select ROW_NUMBER()over( partition by officeid order by userid )as id, * from tbl_User sqlserver中表示根据officeid分组 然后根据userid排序

select ROW_NUMBER()over( order by officeid )as id, * from tbl_User 根据officeid排序

MySQL实现上面两个例子用一下方法

实例数据创建

DROP TABLE
IF EXISTS heyf_t10;

CREATE TABLE heyf_t10 (
empid INT,
deptid INT,
salary DECIMAL (10, 2)
);

INSERT INTO heyf_t10
VALUES
(1, 10, 5500.00),
(2, 10, 4500.00),
(3, 20, 1900.00),
(4, 20, 4800.00),
(5, 40, 6500.00),
(6, 40, 14500.00),
(7, 40, 44500.00),
(8, 50, 6500.00),
(9, 50, 7500.00);

call testrank() ---分组排序
create PROCEDURE testrank()
BEGIN
set @num=0;
set @pdept=null;
SELECT result.empid,result.deptid,result.salary,result.rank FROM (SELECT s.empid,s.deptid,s.salary,
if(@pdept=s.deptid,@num:=@num+1,@num:=1) as rank,
@pdept:=s.deptid
FROM heyf_t10 s order by s.deptid asc ,s.salary desc )result ;
end

排序
call testpaixus()
create PROCEDURE testpaixus()
BEGIN
set @num = 0 ;
select s.empid,s.deptid,s.salary, (@num:=@num+1 )as rank from heyf_t10 s  order by s.deptid ;根据deptid排序

set @num = 0 ;
select id ,uaddress, uname, (@num:=@num+1 )as rank  from testd order BY uname desc 根据 uname排序

end

点点积累,加油!收获满满的喜悦。

上一篇:oracle ROW_NUMBER() OVER(PARTITION BY '分组' ORDER BY '排序' DESC) 用法


下一篇:php接口签名验证