mysql 实现 oracle ROW_NUMBER() OVER(PARTITION BY)

测试数据:
建表

create table Student1
(
Sno varchar(20) not null primary key,
Sname varchar(20) not null,
Ssex varchar(20) not null,
score int,
clas varchar(20)
)

插入数据:

insert into student1 values ('108','曾华','男',65,95033);
insert into student1 values (105,'匡明','男',65,95031);
insert into student1 values (107,'王丽','女',88,95033);
insert into student1 values (101,'李军','男',33,95033);
insert into student1 values (109,'王芳','女',20,95031);
insert into student1 values (103,'陆君','女',11,95031);

1.首先是一个字段分组:按班级分组,成绩排序

首先我们实现通过 score 排序
oracle

select t.*,rank() over(PARTITION by clas order by score desc) from Student1 t

mysql 实现 oracle ROW_NUMBER() OVER(PARTITION BY)_第1张图片

mysql

SELECT
  *,
  @last := IF(@first = t.clas, @last + 1, 1) as rank,
  @first := t.clas
FROM Student1 t,
     (SELECT
         @last := 0,
         @first := NULL) c
ORDER BY t.clas, t.score desc

2. 两个字段分组:按班级性别分组,成绩排序

oracle

select t.*,rank() over(PARTITION by ssex,clas order by score desc) from Student1 t

mysql 实现 oracle ROW_NUMBER() OVER(PARTITION BY)_第2张图片

mysql

SELECT
  *,
  @last := IF(@first = t.clas and @sex=t.ssex, @last + 1, 1) as rank,
  @first := t.clas,
  @sex:=t.ssex
FROM Student1 t,
     (SELECT
         @last := 0,
         @first := NULL) c
ORDER BY t.clas,t.ssex, t.score desc

mysql 实现 oracle ROW_NUMBER() OVER(PARTITION BY)_第3张图片

你可能感兴趣的:(#,MySql)