mysql的rank函数,if函数的使⽤========================= 例⼦ ========================================
记录表:table_test ;
字段:banji 班级;AvgS 平均分;pm 排名;
解决⽅法:
SELECT
M.*
FROM
(
SELECT A.*,@rank:=@rank+1as pm
FROM
(
SELECT banji,avg(score) as AvgS FROM table_test GROUP BY banji ORDER BY AvgS DESC
) A ,(SELECT@rank:=0) B
) M
ORDER BY M.banji
==============================>>>>>>>>输出结果:
banji AvgS pm
-----------------------
'1', '47.0000', '1'
'2', '12.0000', '3'
'5', '38.5000', '2'
例2 我们以 a 分组,查询 b列最⼤的2个值。
1.创建表
Create Table: CREATE TABLE `sam` (
`a` int(11) DEFAULT NULL,
`b` int(11) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8
2.插⼊模拟数据
INSERT INTO `sam` VALUES (1,10),(1,15),(1,20),(1,25),(2,20),(2,22),(2,33),(2,45);
+------+------+
| a | b |
+------+------+
| 1 | 10 |
| 1 | 15 |
| 1 | 20 |
| 1 | 25 |
| 2 | 20 |
| 2 | 22 |
| 2 | 33 |
| 2 | 45 |
+------+------+
3.SQL实现 我们以a分组,查询b列最⼤的2个值。这条sql要怎么写了?
select a, b, rownum, rank
from
(
SELECT
ff.a,
ff.b,
@rownum:=@rownum+1 rownum, --排序后的⾏号
if(@pa=ff.a, --与上个a⽐较,相同继续+1排序,不同说明组别不⼀样,从1开始重新排
@rank:=@rank+1,
@rank:=1
) as rank,
@pa:=ff.a
rank函数怎么用
FROM
(select a,b from sam group by a,b order by a asc,b desc) ff,
(select@rank:=0,@rownum:=0,@pa=null) tt
) result
HAVING rank <=2; --rank起到按a排序后标记顺序以及筛选的作⽤
4.结果:
+------+------+--------+------+
| a | b | rownum | rank |
+------+------+--------+------+
| 1 | 25 | 1 | 1 |
| 1 | 20 | 2 | 2 |
| 2 | 45 | 5 | 1 |
| 2 | 33 | 6 | 2 |
+------+------+--------+------+
4 rows in set (0.00 sec)
例3
下⾯不仅要对成绩进⾏排名,⽽且需要相同成绩的具有相同的排名。
表:score,有三个字段,id,name,score
select
tmp.id,tmp.name,tmp.score,
@j:=@j+1as j, -- 顺序⼀直在变⼤
@k:=(case when@pre_score=tmp.score then@k else@j end) as rank, -- 只有在前后⼆次排序值不同时才会使⽤顺序号 @pre_score:=tmp.score as pre_score
from
(select*from score order by score desc) tmp,(select@k :=0,@j:=0, @pre_score:=0) sdcore
-- @k 表⽰最终的排名(相同值时序号相同)
-- @j 表⽰顺序排名
-- @pre_score上⼀次排序值
发布评论