Take out the first N records in each group in MySql

The requirement is like this (a question on CSDN): There is a table in mysql: article (field: id, type, date), type has 1-10, 10 types. Now use SQL to find the set of the top N data with the latest time in each type.

There should be many ways to achieve this problem. Let's talk about the realization of a master I saw on the Internet (I realized it with a SQL statement, and I personally feel very good, so I will share it with you.

select
	a1.*
from
	article a1
inner join(
		select
			a.type,
			a.date
		from
			article a
		left join article b on
			a.type = b.type
			and a.date <= b.date
		group by
			a.type,
			a.date
		having
			count( b.date )<= 2
	) b1 on
	a1.type = b1.type
	and a1.date = b1.date
order by
	a1.type,
	a1.date desc

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325012545&siteId=291194637