Sql分组内排序

前两天同学遇到这样一个需求。用sql找出成绩表中 各科前10名学生名单。 成绩表字典我就不说明了,大家都懂。

他说只用sql处理。我当时首先想到的是存储过程、游标之类的。

过后,他又提起这个事情来。告诉我说不用存储过程就可以。然后给我贴了实例出来。

 

DROP TABLE IF EXISTS `ads_credit_applylog`;

CREATE TABLE `ads_credit_applylog` (
  `id` varchar(20) NOT NULL,
  `customer_id` varchar(20) DEFAULT NULL,
  `ips` int(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


-- ----------------------------
-- Records of ads_credit_applylog
-- ----------------------------
INSERT INTO `ads_credit_applylog` VALUES ('1', '15588', '921');
INSERT INTO `ads_credit_applylog` VALUES ('2', '15588', '597');
INSERT INTO `ads_credit_applylog` VALUES ('3', '15588', '483');
INSERT INTO `ads_credit_applylog` VALUES ('4', '15588', '1000');
INSERT INTO `ads_credit_applylog` VALUES ('5', '12619', '421');
INSERT INTO `ads_credit_applylog` VALUES ('6', '12619', '358');
INSERT INTO `ads_credit_applylog` VALUES ('7', '12619', '523');
INSERT INTO `ads_credit_applylog` VALUES ('8', '12619', '879');




select  (@i := case  when  @pre_parent_code=customer_id then @i + 1 else 1 end )  rownum,                       
customer_id,ips,(@pre_parent_code:=customer_id)                      
from 
#ads_credit_applylog ,
#需要先排好序
(select customer_id,ips from ads_credit_applylog order by customer_id,ips desc ) a , 
                   
(SELECT  @i := 0, @pre_parent_code:='') AS b                     
group  by   customer_id ,ips desc 
order  by   customer_id,ips desc,rownum 

利用临时表来解决排序问题。

运行结果如下。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值