MySQL extracts the first N records from each group.

Source: Internet
Author: User

The requirement is as follows (a problem on csdn): There is a table in MySQL: article (field: ID, type, date), type has 1-10, 10 types. Now we need to use SQL to find a collection of the First n data of the latest time in each type.

 

There should be many ways to implement this problem. Next we will talk about the implementation of a master we can see on the Internet (using an SQL statement, I personally feel very good, so I will share 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

Note: 2 in the preceding SQL statement represents N as mentioned above.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.