mysql实现dense_rank_mysql模拟rank, dense_rank

http://stackoverflow.com/questions/532878/how-to-perform-grouped-ranking-in-mysql

CREATE TABLE `test` (

`student_id` int(10) unsigned NOT NULL AUTO_INCREMENT,

`subject` varchar(10) CHARACTER SET latin1 DEFAULT NULL,

`score` tinyint(4) DEFAULT NULL,

PRIMARY KEY (`student_id`)

) ENGINE=MyISAM DEFAULT CHARSET=utf8;

insert into `test`(`id`,`student_id`,`subject_name`,`score`) values (1,1,'yw',80);

insert into `test`(`id`,`student_id`,`subject_name`,`score`) values (2,1,'sx',90);

insert into `test`(`id`,`student_id`,`subject_name`,`score`) values (3,2,'yw',85);

insert into `test`(`id`,`student_id`,`subject_name`,`score`) values (4,2,'sx',95);

insert into `test`(`id`,`student_id`,`subject_name`,`score`) values (5,3,'yw',70);

insert into `test`(`id`,`student_id`,`subject_name`,`score`) values (6,3,'sx',100);

insert into `test`(`id`,`student_id`,`subject_name`,`score`) values (7,4,'yw',70);

insert into `test`(`id`,`student_id`,`subject_name`,`score`) values (8,4,'sx',70);

subject_name: 科目 yw:语文 sx:数学

dense_rank

select subject_name as sbn , student_id as sid, score,

@rank:=case when @sn <> subject_name then 1 when @score <> score then @rank+1 else @rank+0 end as rank,

@sn := subject_name as sn,

@score := score as score

from `test` p,

(select @rank := 0) r,

(select @sn := '') u,

(select @score := -1) i

order by subject_name, score;

result:

sbnsidscoreranksnscore

sx4701sx70

sx1902sx90

sx2953sx95

sx31004sx100

yw3701yw70

yw4701yw70

yw1802yw80

yw2853yw85

rank

select subject_name as sbn, student_id as sid, score,

@rank:=case when @sn <> subject_name then 1 when @score <> score then @rank+@range else @rank+0 end as rank,

@range:=case when @sn <> subject_name then 1 when @score = score then @range+1 else 1 end as ran ,

@sn := subject_name as sn, @score := score as sc

from `test` p, (select @rank := 0) r,

(select @sn := '') u, (select @score := -1) i, (select @range := 1) g

order by subject_name, score;

sbnsidscorerankransnsc

sx47011sx70

sx19021sx90

sx29531sx95

sx310041sx100

yw37011yw70

yw47012yw70

yw18031yw80

yw28541yw85

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2012-06-14 14:52

浏览 988

分类:数据库

评论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值