查出每个分组的前n条记录

现实可能有如下应用:

参考如下: http://sqlfiddle.com/#!2/22cbf/1

create table `person`
(
  `person` varchar(10),
  `group` int,
  `age` int
);

insert into `person` values
('Bob', 1, 32),
('Jill', 1, 34),
('Shawn', 1, 42),
('Jake', 2, 29),
('Paul', 2, 36),
('Laura', 2, 39);


// 查询语句
SELECT a.person, a.group, a.age FROM person AS a WHERE (SELECT COUNT(*) FROM person AS b WHERE b.group = a.group AND b.age >= a.age) <= 2 ORDER BY a.group ASC, a.age DESC


值的一看的文章

一句SQL:取得相同sortid的结果集,每种 ID三条数据
http://www.neatstudio.com/show-1934-1.shtml

How to select the first/least/max row per group in SQL

http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/

Yoyo 「二是一种不三不四的态度」

男 1990.12.22 429660248@qq.com