我知道mysql中没有rank函数,但我无法在mysql中实现rank函数的wokaround。有人可以来救援吗?
以下是我想要实现的目标。
ID Type Priority Expected Rank
1 1 1 1
1 1 2 2
1 2 1 1
1 2 2 2
2 1 1 1
2 2 1 1
3 1 1 1
3 1 2 2
3 2 1 1
3 2 2 2
4 1 1 1
4 2 1 1
对于每个ID和类型,我想按优先级排序
提前致谢。
答案 0 :(得分:1)
这是你可以做的
select id,type,priority,rank
from (
select t.*,
@rank := if(
@prev_id = id and
@prev_type = type
and @prev_priority != priority,@rank+1,1
) as rank,
@prev_id := id,
@prev_type:= type,
@prev_priority := priority
from test t,
(select @rank:=1,@prev_type:=0,@prev_priority:=0,@prev_id:=0)r
order by id,type,priority
)s ;
将表名更改为test
以下是测试用例
mysql> insert into test values (1,1,1),(1,1,2),(1,2,1),(1,2,2),(2,1,1),(2,2,1),(3,1,1),(3,1,2),(3,2,1),(3,2,2);
Query OK, 10 rows affected (0.06 sec)
Records: 10 Duplicates: 0 Warnings: 0
mysql> select * from test ;
+------+------+----------+
| id | type | priority |
+------+------+----------+
| 1 | 1 | 1 |
| 1 | 1 | 2 |
| 1 | 2 | 1 |
| 1 | 2 | 2 |
| 2 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 1 | 1 |
| 3 | 1 | 2 |
| 3 | 2 | 1 |
| 3 | 2 | 2 |
+------+------+----------+
10 rows in set (0.00 sec)
mysql> select id,type,priority,rank from ( select t.*, @rank := if(@prev_id = id and @prev_type = type and @prev_priority != priority,@rank+1,1) as rank, @prev_id := id,@prev_type:= type, @prev_priority := priority from test t,(select @rank:=1,@prev_type:=0,@prev_priority:=0,@prev_id:=0)r order by id,type,priority)s ;
+------+------+----------+------+
| id | type | priority | rank |
+------+------+----------+------+
| 1 | 1 | 1 | 1 |
| 1 | 1 | 2 | 2 |
| 1 | 2 | 1 | 1 |
| 1 | 2 | 2 | 2 |
| 2 | 1 | 1 | 1 |
| 2 | 2 | 1 | 1 |
| 3 | 1 | 1 | 1 |
| 3 | 1 | 2 | 2 |
| 3 | 2 | 1 | 1 |
| 3 | 2 | 2 | 2 |
+------+------+----------+------+
10 rows in set (0.00 sec)