日期:2014-05-17 浏览次数:21215 次
MYSQL实现分组排序( row_number()over()功能 )
drop table if exists tb;
create table tb(col1 int,col2 int);
insert tb
select 1,2 union all
select 1,3 union all
select 1,4 union all
select 2,9 union all
select 2,7 union all
select 2,8 union all
select 3,1 union all
select 3,6;
select *
from
( select
a.*,
@rownum:=@rownum+1 as 序号,
if(@pdept=a.col1,@rank:=@rank+1,@rank:=1) as 排名, @pdept:=a.col1
from
(select * from tb order by col1 asc ,col2 desc ) a ,(select @rownum :=0 , @pdept := null ,@rank:=0)b)result;
/*
Col1 col2 序号 排名
1 4 1 1 1
1 3 2 2 1
1 2 3 3 1
2 9 4 1 2
2 8 5 2 2
2 7 6 3 2
3 6 7 1 3
3 1 8 2 3
*/