【MySql】关于排名计算的几种方法汇总及算法分析
USE test; #转到test库
DROP TABLE IF EXISTS `stu_mark`; #如果这个表存在,就将这个表删除
CREATE TABLE `stu_mark` (
`id` INT(10) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(20) NOT NULL,
`mark` INT(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8; #创建表,定义字段及字段类型
INSERT INTO stu_mark(`name`, `mark`)
VALUES ('lisi',10),('zhangsan',20),('wangwu',20),('zhaoliu',30),('liuqi',50),('anjiu',100);
#在表中插入数据
SELECT `name`, `mark`,convert(sor,signed) FROM(
SELECT `name`, `mark`
,(CASE WHEN @tMark=mark THEN @tm ELSE @tm :=@tm+1 END) AS sor
,(@tMark:=mark) AS tm
FROM `stu_mark` AS m ,(SELECT @tm :=0,@tMark:=0) AS t1
ORDER BY mark DESC
) AS t2
ORDER BY t2.sor desc
SELECT merchant_no,trans_amount+0,
trans_time,
(SELECT count(0) FROM (SELECT distinct merchant_no m,trans_time s FROM transaction_detail_202006 where merchant_no in('207631005231291','215201004582046') and trans_time>'2020-06-30') tmp WHERE s >= trans_time and m=merchant_no ) Rank,
(SELECT count(0) FROM (SELECT distinct merchant_no m,trans_amount+0 s FROM transaction_detail_202006 where merchant_no in('207631005231291','215201004582046') and trans_time>'2020-06-30') tmp WHERE s >= trans_amount+0 and m=merchant_no) Rank2
FROM transaction_detail_202006 where merchant_no in('207631005231291','215201004582046') and trans_time>'2020-06-30'
ORDER BY trans_time,trans_amount+0 desc;