Search code examples
mariadbpivot-table

MariaDB: Show TOP 5 results per member (in pivot table)


I have a table in my MariaDB database that looks like this (simplified example);

Date Member Grade
1-3-2023 Paul 10
2-3-2023 Paul 6
3-3-2023 Paul 9
4-3-2023 Paul 9
5-3-2023 Paul 6
6-3-2023 Paul 5
7-3-2023 Paul 3
2-3-2023 Sarah 8
3-3-2023 Sarah 9

and so on.

What I'd like to do is show the TOP 5 Grades per member (preferably sorted by date) in a pivot table. If there is less than 5 results I'd like the rest to be either displayed as 0 or NULL (either one is fine). Each combination of grade+date should be treated as a seperate result. In the above table the top 5 grades of Paul should be 10,9,9,6,6

So to illustrate, the desired result would be;

Member Grade 1 Grade 2 Grade 3 Grade 4 Grade 5
Paul 10 6 9 9 6
Sarah 8 9 0 0 0

I can't seem to figure out how to do this. I know how to create a pivot table but the ones I created before were grouped by a certain other field (like month). I'm not quite sure how to do this with the Top 5 results. Certainly not when having them in the order of the date the grade was achieved.


Solution

  • Solved after suggestion by Barmar.

    For anyone struggling with this question, I got my desired result by using this query;

    SELECT Member,
      MAX(CASE WHEN Rank = 1 THEN Grade END) as '1',
      MAX(CASE WHEN Rank = 2 THEN Grade END) as '2',
      MAX(CASE WHEN Rank = 3 THEN Grade END) as '3',
      MAX(CASE WHEN Rank = 4 THEN Grade END) as '4',
      MAX(CASE WHEN Rank = 5 THEN Grade END) as '5',
          FROM (SELECT RANK() OVER(PARTITION BY member ORDER BY Grade DESC) Rank, Member, Grade FROM table) pivot
    GROUP BY Member