1、实现row_number()
select user_nm
, login_time
, @row_num := @row_num + 1 as rank_num
from (
select 'zhang' as user_nm, '2019-01-03 12:30:20' as login_time
union all
select 'zhang' as user_nm, '2019-01-02 12:30:20' as login_time
union all
select 'zhang' as user_nm, '2019-01-02 14:30:20' as login_time
union all
select 'li' as user_nm, '2019-01-04 12:30:20' as login_time
union all
select 'li' as user_nm, '2019-01-05 12:30:20' as login_time
union all
select 'li' as user_nm, '2019-01-06 12:30:20' as login_time
union all
select 'li' as user_id, '2019-01-07 12:30:20' as login_time
union all
select 'wang' as user_nm, '2019-01-07 12:30:20' as login_time
union all
select 'wang' as user_nm, '2019-01-04 14:30:20' as login_time
union all
select 'wang' as user_nm, '2019-01-05 12:30:20' as login_time
union all
select 'wang' as user_nm, '2019-01-06 12:30:20' as login_time
order by user_nm, login_time
) a, (select @row_num := 0) as b;
执行结果:
2、实现row_number(partition by)
select user_nm
, login_time
, @row_num := case when @group_nm = user_nm then @row_num := @row_num + 1 else 1 end as rank_num
, @group_nm := user_nm as user_nm2
from (
select 'zhang' as user_nm, '2019-01-03 12:30:20' as login_time
union all
select 'zhang' as user_nm, '2019-01-02 12:30:20' as login_time
union all
select 'zhang' as user_nm, '2019-01-02 14:30:20' as login_time
union all
select 'li' as user_nm, '2019-01-04 12:30:20' as login_time
union all
select 'li' as user_nm, '2019-01-05 12:30:20' as login_time
union all
select 'li' as user_nm, '2019-01-06 12:30:20' as login_time
union all
select 'li' as user_id, '2019-01-07 12:30:20' as login_time
union all
select 'wang' as user_nm, '2019-01-07 12:30:20' as login_time
union all
select 'wang' as user_nm, '2019-01-04 14:30:20' as login_time
union all
select 'wang' as user_nm, '2019-01-05 12:30:20' as login_time
union all
select 'wang' as user_nm, '2019-01-06 12:30:20' as login_time
order by user_nm, login_time
) a, (select @row_num := 0, @group_nm := '') as b;
执行结果: