MySQL group query before n data

Source: Internet
Author: User

Build table:

CREATE TABLE Hard (
ID INT,
AA varchar (50),
BB INT,
PRIMARY Key (ID)
)
INSERT into hard values (1, ' a ', 9)
INSERT into hard values (2, ' a ', 7)
INSERT into hard values (3, ' a ', 8)
INSERT into hard values (4, ' a ', 6)

INSERT into hard values (5, ' B ', 2)
INSERT into hard values (6, ' B ', 3)
INSERT into hard values (7, ' B ', 4)

INSERT into hard values (8, ' C ', 1)
INSERT into hard values (9, ' C ', 8)
INSERT into hard values (, ' C ', 2)

Query the table with a maximum of two numbers per group:

Select A.* from Hard a Where (select count (*) from hard where aa = A.aa and bb > A.bb) < 2 ORDER BY a.aa,a.bb DESC

Here 2 is n

(Query single table non-grouped top n max data: Select DISTINCT BB from hard ORDER BY bb desc limit 2)

Result diagram:

Principle Analysis:

MySQL group query before n data

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.