低版本mysql 实现row_number() ,rank() ,dense_rank()及其窗口函数

测试表

 create table  test (id int(4) ,  name VARCHAR(10) )
  • row_number() 实现
SELECT t.name , t.id, (@cur_rank := @cur_rank + 1) ranking
FROM  test t , (SELECT @cur_rank := 0) r
ORDER BY id  DESC;
  • ROW_NUMBER() over(partiton by name ORDER BY id DESC) 实现 @pre_name
    := t.name 要保留
 select  t.name, t.id,
IF(@pre_name = t.name, @cur_rank := @cur_rank + 1, @cur_rank := 1) ranking,
@pre_name := t.name
FROM test t, (SELECT @cur_rank := 0, @pre_name := NULL) r
ORDER BY name, id DESC; 

  • rank() 实现
SELECT t.id,
@rank_counter := @rank_counter + 1,
IF(@pre_id = t.id, @cur_rank, @cur_rank := @rank_counter) ranking,
@pre_id := t.id
FROM test t, (SELECT @cur_rank :=0, @pre_id := NULL, @rank_counter := 0) r
ORDER BY t.id DESC; 
SELECT t.id,
@rank_counter := @rank_counter + 1,
(CASE WHEN @pre_id = t.id THEN @cur_rank
       WHEN @pre_id := t.id THEN @cur_rank := @rank_counter
  END  ) ranking
FROM test t, (SELECT @cur_rank :=0, @pre_id := NULL, @rank_counter := 0) r
ORDER BY t.id DESC; 

  • RANK() OVER(PARTITION BY NAME ORDER BY ID DESC)
SELECT t.name , t.id ,
IF(@pre_name = t.name,  @rank_counter := @rank_counter + 1,  @rank_counter := 1) t_rank,
IF(@pre_name = t.name,  IF(@pre_id = t.id, @cur_rank, @cur_rank := @rank_counter),@cur_rank := 1) ranking,
@pre_id := t.id t_id,
@pre_name := t.name t_name
FROM test t , (SELECT @cur_rank := 0, @pre_name := NULL, @pre_id := NULL, @rank_counter := 1)r
ORDER BY t.name, t.id DESC; 

  • DENSE_RANK() 实现
SELECT t.id,
IF(@pre_id = t.id, @cur_rank, @cur_rank := @cur_rank + 1) ranking,
@pre_id := t.id
FROM test t , (SELECT @cur_rank :=0, @pre_id = NULL) r
ORDER BY t.id DESC; 

SELECT t.name , t.id,
( CASE  WHEN @pre_id = t.id THEN @cur_rank
        WHEN @pre_id := t.id THEN @cur_rank := @cur_rank + 1
  END ) ranking
FROM test t, (SELECT @cur_rank :=0, @pre_id = NULL) r
ORDER BY t.id DESC; 
  • DENSE_RANK() OVER(PARTITION BY NAME ORDER BY ID DESC) 实现
SELECT t.name, t.id,
IF(@pre_name = t.name, IF(@pre_id = t.id, @cur_rank, @cur_rank := @cur_rank + 1),  @cur_rank := 1) ranking,
@pre_id := t.id t_id ,
@pre_name := t.name t_name
FROM test t, (SELECT @cur_rank :=0, @pre_id = NULL, @pre_name := NULL) r
ORDER BY t.name, t.id DESC; 
SELECT t.name,t.id,
IF(@pre_id = t.id, @cur_rank, @cur_rank := @cur_rank + 1) temp1,
@pre_id := t.id temp2,
IF(@pre_name = t.name, @cur_rank, @cur_rank := 1) ranking,
@pre_name := t.name
FROM test t, (SELECT @cur_rank :=0, @pre_id = NULL, @pre_name := NULL) r
ORDER BY t.name, t.id DESC; 

你可能感兴趣的:(mysql,mysql)