从表中求和或计数仅少数/有限行

时间:2017-02-03 21:48:51

标签: mysql sql database

我有一个学生标记表,我按学科推荐学生分数。我想为每个学生总共最多3门科目。并且还想要查看学生的主题数或者该表组中存在多少个主题。这是我的表结构。

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
----------------------------------

我正在尝试但无法理解我将如何限制连接表我的示例查询

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

您知道的查询输出,它将显示所有行的总和。但我想像以前的表“my_expected_table”

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

1 个答案:

答案 0 :(得分:2)

在MySQL中这很痛苦。最好的方法是使用变量:

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;

注意:

  • 我没有加入学生表,这显然是要添加的。
  • 这将3个标记定义为&#34;具有最低ID&#34;的行上的3个标记。这由第二个order by密钥确定。