Find top N records for each group in MySQL

In this post, I am giving you a full demonstration on finding top N records for each group in MySQL.

Today morning, I was working on one report and requirement is to find top 2 employee working hours for each employee.

I have tried many scripts and finally got the solution which is also forcing me to write a good post on this.

First, create sample data,

The Second step is to find a top N working hour by each employee.


MySQL Top N Record for Each Group

Now see above result, each employee has two top 2 record base on working hours.

In above query I have used GROUP_CONCAT, and FIND_IN_SET.
GROUP_CONCAT groups column value into a single string and FIND_IN_SET is used to get the position of the string in a comma delimited string list.

You can change the value of 2 to N for your customized report.

Please share your ideas and opinions about this topic with me, your contribution will add true value to this topic.
If anyone has doubts on this topic then please do let me know by leaving comments or send me an email.

If you like this post, then please share it with others.
Please follow, I will share my experience towards the success of Database Research and Development Activity.

I put up a post every day, please keep reading and learning.
Discover Yourself, Happy Blogging !
Anvesh M. Patel.

More from

Leave a Reply

Be the First to Comment!

Notify of