Here is the table:
User
Name: Subject:
Peter Math
Mary Chinese
Mary Computer
Mary Hist
Mary PE
Mary English
Peter Art
Chris English
Chris Computer
Peter Computer
Paul Math
I would like to get the the top appear in name, and return top 4 result should be subject name. For example, in this case top appear name is Mary, and base on the order in subject, the Chinese , Computer, English, so I would like to have the result:
Mary Chinese
Mary Computer
Mary English
Mary Hist
If Mary is not the most enough to show the result, the second people will be the follow, like, let say the table will like this:
Name: Subject:
Peter Math
Mary Chinese
Mary Computer
Mary Hist
Peter Art
Chris English
Chris Computer
Peter Computer
Paul Math
The result will be,
Mary Chinese
Mary Computer
Mary Hist
Peter Art
Because Mary is the most appear, so Mary will return, but Mary is not enough to fill in 4 positions, so the second most appear will take the place, in this case, we use Peter.
SELECT user.name, user.subject FROM user INNER JOIN ( SELECT name, COUNT(1) AS occurrences FROM user GROUP BY name ) AS user_occurrences ON user.name = user_occurrences.name ORDER BY user_occurrences.occurrences DESC, user.name ASC, user.subject ASC LIMIT 4edit This might perform better, depending on the RDBMS you’re using and the size of the dataset. Try both and compare.