Mysql——》group by分组后,添加行号

推荐链接:
    总结——》【Java】
    总结——》【Mysql】
    总结——》【Redis】
    总结——》【Kafka】
    总结——》【Spring】
    总结——》【SpringBoot】
    总结——》【MyBatis、MyBatis-Plus】
    总结——》【Linux】
    总结——》【MongoDB】
    总结——》【Elasticsearch】

Mysql——》group by分组后,添加行号

一、场景

按user_id分组,按分数和倒序排列,添加行号

CREATE TABLE `score` (
  `id` int NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `user_id` int NOT NULL COMMENT '用户ID',
  `course_id` int NOT NULL COMMENT '课程ID',
  `score` int NOT NULL COMMENT '分数',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;


INSERT INTO `xiaoxian`.`score` (`id`, `user_id`, `course_id`, `score`) VALUES (1, 1, 1, 90);
INSERT INTO `xiaoxian`.`score` (`id`, `user_id`, `course_id`, `score`) VALUES (2, 1, 2, 70);
INSERT INTO `xiaoxian`.`score` (`id`, `user_id`, `course_id`, `score`) VALUES (3, 1, 3, 88);
INSERT INTO `xiaoxian`.`score` (`id`, `user_id`, `course_id`, `score`) VALUES (4, 2, 2, 90);
INSERT INTO `xiaoxian`.`score` (`id`, `user_id`, `course_id`, `score`) VALUES (5, 2, 3, 66);
INSERT INTO `xiaoxian`.`score` (`id`, `user_id`, `course_id`, `score`) VALUES (6, 2, 4, 92);
INSERT INTO `xiaoxian`.`score` (`id`, `user_id`, `course_id`, `score`) VALUES (7, 3, 1, 99);
INSERT INTO `xiaoxian`.`score` (`id`, `user_id`, `course_id`, `score`) VALUES (8, 3, 3, 90);
INSERT INTO `xiaoxian`.`score` (`id`, `user_id`, `course_id`, `score`) VALUES (9, 4, 4, 88);

image.png

二、实现

SELECT
	a.*,
	@rn := @rn + 1 AS rn 
FROM
	( SELECT user_id, sum( score ) score FROM score WHERE 1 = 1 GROUP BY user_id ORDER BY score DESC ) a,(
	SELECT
	@rn := 0 
	) AS b

image.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值