Mysql查询显示一学期所有学生的成绩

时间:2018-04-09 06:29:51

标签: mysql

我有一个semester_student_marks表,其结构如下 -

<table border="1">
<tr>
<th>Semester Id</th><th>Student Id</th><th>Subject Id</th><th>Marks</th>
</tr>
<tr><td>1</td><td>1234</td><td>1</td><td>55</td></tr>
<tr><td>1</td><td>1234</td><td>2</td><td>65</td></tr>
<tr><td>1</td><td>3456</td><td>1</td><td>75</td></tr>
<tr><td>1</td><td>3456</td><td>2</td><td>85</td></tr>
</table>

<br><br>


<table border="1">
<tr>
<th>Student Id</th><th>Subject 1</th><th>Subject 2</th>
</tr>
<tr><td>1234</td><td>55</td><td>65</td></tr>
<tr><td>3456</td><td>75</td><td>85</td></tr>

</table>

我尝试了以下查询 -

select m.student_id,
       if(m.subject_id=8,m.marks,0) as 'S1',
       if(m.subject_id=9,m.marks,0) as 'S2',
       if(m.subject_id=10,m.marks,0) as 'S3' 
from (select student_id, 
             subject_id, 
             marks 
      from program_exam_marks t 
      where semester_id=1) m;

但是每个学生主题的结果将显示在如下的单独行中 -

+------------+------+------+------+
| student_id | S1   | S2   | S3   |
+------------+------+------+------+
|       1234 |   55 |    0 |    0 |
|       1234 |    0 |   67 |    0 |
|       1234 |    0 |    0 |   74 |
|     654321 |   55 |    0 |    0 |
|     654321 |    0 |   87 |    0 |
|     654321 |    0 |    0 |   60 |
+------------+------+------+------+

如何将结果作为 -

+------------+------+------+------+
| student_id | S1   | S2   | S3   |
+------------+------+------+------+
|     1234   |   55 |   67 |   74 |       
|     654321 |   75 |   87 |   60 |
+------------+------+------+------+

我的SQL技能是最基本的,所以任何/所有建议/解决方案都将非常感激。

谢谢。

2 个答案:

答案 0 :(得分:2)

你的事情过于复杂,你甚至不需要子查询。只需使用学生的条件聚合,并使用SUM CASE个表达式来确定标记。

SELECT
    student_id,
    SUM(CASE WHEN subject_id = 8  THEN marks ELSE 0 END) AS S1,
    SUM(CASE WHEN subject_id = 9  THEN marks ELSE 0 END) AS S2,
    SUM(CASE WHEN subject_id = 10 THEN marks ELSE 0 END) AS S3
FROM program_exam_marks
WHERE semester_id = 1
GROUP BY
    student_id;

答案 1 :(得分:0)

您可以使用学生的条件聚合,并使用SUM if expressions作为标记。

select m.student_id,
           SUM(if(m.subject_id=8,m.marks,0)) as 'S1',
           SUM(if(m.subject_id=9,m.marks,0)) as 'S2',
           SUM(if(m.subject_id=10,m.marks,0)) as 'S3' 
from (select student_id, 
             subject_id, 
             marks 
      from program_exam_marks t 
      where semester_id=1) m 
GROUP BY m.student_id;

SELECT student_id,
       SUM(S1) AS S1,
       SUM(S2) AS S2,
       SUM(S3) AS S3
FROM
(select m.student_id,
       if(m.subject_id=8,m.marks,0) as 'S1',
       if(m.subject_id=9,m.marks,0) as 'S2',
       if(m.subject_id=10,m.marks,0) as 'S3' 
from (select student_id, 
             subject_id, 
             marks 
      from program_exam_marks t 
      where semester_id=1) m) T GROUP BY student_id;