我有一个学生标记表,我按学科推荐学生分数。我想为每个学生总共最多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
----------------------------------
答案 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;
注意:
order by
密钥确定。