Home > Database > Mysql Tutorial > 分组后查找每组的前N条记录语句_MySQL

分组后查找每组的前N条记录语句_MySQL

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-01 13:40:57
Original
1088 people have browsed it

bitsCN.com
分组后查找每组的前N条记录语句 Java代码  考你一条sql语句  如有表 student   id  name age  class   1   张1   15     1  2   张2   15     1  3   张3   15     1  4   张4  15     2  5   张5   15     2  6   张6   15     2  7   张7   15     3  8   张8   15     3  9   张9   15     3  10   张10   15     5  11   张11   15     5  
 现在想得到每个班级的前2名学生资料   根据题意是,按class分组,然后取id靠前的两名,相信大多数人都能想到基本组合:    SELECT a.*  FROM student a  ORDER BY a.class, a.id;  另加:Limit 0,2来配合。  (注:MYSQL 中没有top n的写法,取代的是LIMIT。)  Limit 0,n只能取到最前的n位,但如何能取到每个班的前两位呢,就无从下手了。  下面我来具体分析一下这题的解法:  1、获取每个class的前两位:  SELECT a.*  FROM student a  WHERE  (      SELECT COUNT(*)    FROM student    WHERE class = a.class    AND id   bitsCN.com

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template