我有2张这样的表:
学生
ID | Name | Age
1 | Jonh | 20
2 | Smit | 19
3 | David | 28
4 | Simon | 18
5 | Kate | 17
6 | Marry | 20
评分
Studen_ID | mark
1 | 10
1 | 5
2 | 7
3 | 9
3 | 8
我想选择“学生”与Ratting“并显示”报告“这样:
Reporting
ID | Name | Age | avg_mark
1 | Jonh | 20 | 15
2 | Smit | 19 | 7
3 | David | 28 | 17
4 | Simon | 18 | null
5 | Kate | 17 | null
6 | Marry | 20 | null
请帮我这样做。我是如此愚蠢><
由于 阮
答案 0 :(得分:1)
此查询会获得具有评分,显示其姓名和平均分数的学生。如果您想要显示所有这些内容,无论是否评分,请按INNER
更改LEFT
。
SELECT s.id, s.name, s.age, AVG(r.mark) AS avg_mark
FROM student s
INNER JOIN rating r ON s.id = r.student_id
GROUP BY s.id, s.name, s.age
答案 1 :(得分:1)
试试这个:
select id, name, age, sum(mark) as avg_mark from student
left join rating on student.id = rating.student_id
group by student.id, student.name, student.age
但请注意,在您的示例中,avg_mark实际上是总和,而不是平均值。如果你想要平均值(四舍五入),你应该使用avg(mark)
代替:
select id, name, age, avg(mark) as avg_mark from student
left join rating on student.id = rating.student_id
group by student.id, student.name, student.age
两个查询的示例SQL Fiddle。