简体   繁体   中英

Sum or count only few/limited row from a table

I have a student mark table where i putted student marks by subject. I wanted to take sum of maximum 3 subjects for each student. And also wanted to see subject count or how many subjects mark entry exist on this table group by a student. This is my table structure.

students
----------------------
id |    name    | roll
----------------------
1  | Rahim      | 201
2  | Kalas      | 203
----------------------
student_marks
--------------------------------
id | student_id | subject | mark
--------------------------------
1  |    1       |   A     | 10
2  |    1       |   B     | 5
3  |    1       |   C     | 10
4  |    1       |   D     | 5
5  |    2       |   A     | 10
6  |    2       |   B     | 10
--------------------------------
my_expected_table
----------------------------------
student_id | student_name | sum
----------------------------------
1          | Rahim        | 25
2          | Kalas        | 20
----------------------------------

I am trying but can't understand how would i give limit on join table my sample query here

SELECT students.id as student_id,
       students.name as student_name,
       sum(student_marks.mark) as sum
From students
inner join student_marks on student_marks.student_id = students.id
Group by student_marks.student_id

the query output you know, it will show sum of all row. but i want like previous table "my_expected_table"

----------------------------------
student_id | student_name | sum
----------------------------------
1          | Rahim        | 30
2          | Kalas        | 20
----------------------------------

This is painful to do in MySQL. The best way uses variables:

select sm.student_id, count(*) as num_marks,
       sum(case when rn <= 3 then mark end) as random_3_sum
from (select sm.*,
             (@rn := if(@s = student_id, @rn + 1,
                        if(@s := student_id, 1, 1)
                       )
             ) as rn
      from student_marks sm cross join
           (select @rn := 0, @s := -1) params
      order by student_id, id
     ) sm
group by sm.student_id;

Notes:

  • I didn't both with the join to the student table, that is obvious to add.
  • This defines 3 marks as "the 3 marks on the rows with the lowest id". This is determined by the second order by key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM