Ok so I have changed it from columns to rows instead đ
Im saving grades for students. I have a MySQL table called “grade” with three columns called “subject”, “points” and “userId” with 18 rows with different subjects where each subject can have one of the values 20, 17.5, 15 or 12.5
So all users have the same “subjects” but can have different “points”
"subject" "points" "userId" svenska 20 23 engelska 15 23 bild 12.5 23 biologi 15 23 matte 17.5 23 fysik 20 23 historia 12.5 23 hemkunskap 15 23 kemi 17.5 23 historia 20 23 idrott 12.5 23 moderansprÄk 15 23 modersmÄl 17.5 23 musik 12.5 23 religion 20 23 samhÀllskunskap 15 23 slöjd 12.5 23 teknik 17.5 23
I need to select and sum the values from the 16 “subjects” that have the highest values out of the 18 “subjects”.
How do I do that? Any input really appreciated, thanks.
Advertisement
Answer
You can use a subquery to get 16 rows with the most points:
select sum(points) from (select g.* from grades g order by points desc limit 16 ) g;
If you want this per user, you would use window functions:
select userid, sum(points) from (select g.*, row_number() over (partition by userid order by points desc) as seqnum from grades g ) g where seqnum <= 16 group by userid