Skip to content
Advertisement

get first row fo each group SQL

I have data like below. I would like to get the top choice for each gender from the following data

I have tried mapping the choices by descending order as below :

BUT, I would like to get the following table where i get the top choice for eachgender :

Advertisement

Answer

If you are runing MySQL 8.0, you can use RANK() in a subquery to rank the records by subject count for each gender, and filter on the top record per group in the outer query (if there are top ties, RANK() preserves them):

In earlier versions, where window functions are not availabe, one option is to filter with a having clause that returns to top count per gender:

Notes:

  • I changed the table aliases to make them more meaningful

  • You should the subject column to the GROUP BY clause to make your query runnable under sql mode ONLY_FULL_GROUP_MODE, which is by default enabled starting MySQL 5.7

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement