Mysql——》group by分组后,在每个组内取前n条数据

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

Mysql——》group by分组后,取每组的前n条数据

一、场景

按course_id分组,按score倒序排列,每个组内取前2个score

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);

在这里插入图片描述

二、实现

方法一

select
* 
from
  (
   select
    @rn:= case when @course_id = a.course_id then @rn + 1 else 1 end as rn
    ,@course_id:= course_id as course_id
    ,score
   from(select * from score x order by course_id,score desc) a
  ) c
where rn <= 2;

在这里插入图片描述

方法二

SELECT
	a.course_id,
	a.score,
	count( b.course_id ) rn 
FROM
	score a
	LEFT JOIN score b ON a.course_id = b.course_id 
	AND a.score < b.score 
GROUP BY
	a.course_id,
	a.score 
HAVING
	count( b.course_id ) < 2 
ORDER BY
	a.course_id,
	a.score DESC;

在这里插入图片描述

方法三

SELECT
	a.course_id,
	a.score,
	count( yy ) rn 
FROM
	(
	SELECT
		a.course_id,
		a.score,
		b.course_id xx,
		b.score yy 
	FROM
		score a
		LEFT JOIN score b ON a.course_id = b.course_id 
		AND a.score < b.score 
	) a 
GROUP BY
	a.course_id,
	a.score 
HAVING
	rn < 2 
ORDER BY
	a.course_id,
	a.score DESC

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值