有时,在做统计的时候,我们需要根据某个字段来计算排名,
下面介绍一下如何使用原生mysql进行排名计算,
首先用户定义一个变量,然后将想要的值存储在变量中,可以在后面的语句中引用该变量。
用户自定义的变量具有会话专一性,即一个客户端创建的自定义变量不能被其他客户端所使用,
当客户端退出时,该客户端创建的所有自定义变量会自动释放。
用户自定义变量的形式:@variableName
设置自定义变量;set @a=0,@b:=0; select @c:=0;
=
只有在set、update时才跟:=一样是赋值作用,其他都是等于作用。:=
赋值作用,不止在set、update时是赋值作用,在select 时也是赋值作用。用于统计的数据表结构与数据:
DROP TABLE IF EXISTS `table_score`;
CREATE TABLE `table_score` (
`s_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'ID',
`s_name` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '姓名',
`score` int(10) NOT NULL COMMENT '成绩',
PRIMARY KEY (`s_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 16 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
INSERT INTO `table_score` VALUES (1, '周一', 20),(2, '周二', 50),(3, '周三', 25),(4, '周四', 88),(5, '周五', 71),(6, '周六', 51),(7, '周日', 36),(8, '赵一', 50),(9, '钱二', 64),(10, '孙三', 81),(11, '李四', 29),(12, '周周', 88),(13, '吴五', 69),(14, '郑七', 75),(15, '王八', 82);
SELECT * FROM table_score ORDER BY score DESC;
SELECT *,
(SELECT count(DISTINCT score) FROM table_score AS b WHERE a.score<b.score)+1 AS rank, #获取排名,并列
(SELECT b.score FROM table_score AS b WHERE b.score>a.score ORDER BY b.score LIMIT 1)-a.score AS subtract #获取和上一名学生成绩的差
FROM table_score AS a WHERE a.s_id = 13; #获取学生周一的成绩排名和与上一名的成绩差
SELECT *,
(SELECT count(DISTINCT score) FROM table_score AS b WHERE a.score<b.score)+1 AS rank #获取排名-并列
FROM table_score AS a ORDER BY rank; #获取学生成绩排名
SELECT a.*,
(@rowNum:=@rowNum+1) AS rank #计算行号
FROM table_score AS a,
(SELECT (@rowNum :=0) ) b
ORDER BY a.score DESC;
SELECT * FROM
(SELECT a.*,(@rowNum:=@rowNum+1) AS rank FROM table_score AS a,(SELECT (@rowNum :=0) ) b ORDER BY a.score DESC) # 学生成绩排名,非并列排名
c WHERE c.s_id = 13;
本文根据原文做了一定修改,原文地址(mysql计算排名)
本文为冯奎原创文章,转载无需和我联系,但请注明来自冯奎博客fengkui.net
最新评论