添加最新结果

时间:2018-03-22 17:40:57

标签: mysql sum

我试图为所有学生评分考试成绩。当我运行MySQL脚本时,它为每次我不想要的测试提供最终分数。如何仅为每个人的最后一次测试获得结果?

               Table test_results
+---------+-------------+-------+-------------+
| student | question_id | score | answered_on |
+---------+-------------+-------+-------------+
| 101     | 1           |   8   |  2017-01-01 |
| 101     | 2           |   9   |  2017-01-01 |   
| 102     | 1           |   8   |  2017-01-01 |  
| 102     | 2           |   7   |  2017-01-01 | 
| 101     | 1           |  10   |  2018-01-01 |
| 101     | 2           |  10   |  2018-01-01 |  
| 102     | 1           |  10   |  2018-01-01 |  
| 102     | 2           |  10   |  2018-01-01 |  
+---------+-------------+-------+-------------+

MySQL脚本如下

SELECT student, SUM(score) AS final_score
FROM  test_results 
WHERE question_id < 3
GROUP BY student;

这给了我以下结果:

+---------+-------------+
| student | final_score |
+---------+-------------+
| 101     |     37      |
| 102     |     35      |
+---------+-------------+

我怎样才能让它看起来像这样?

+---------+-------------+
| student | final_score |
+---------+-------------+
| 101     |     20      |
| 102     |     20      |
+---------+-------------+

1 个答案:

答案 0 :(得分:0)

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(student INT NOT NULL
,question_id INT NOT NULL
,score INT NOT NULL
,answered_on DATE NOT NULL
,PRIMARY KEY(student,question_id,answered_on)
);

INSERT INTO my_table VALUES
(101,1, 8,'2017-01-01'),
(101,2, 9,'2017-01-01'),
(102,1, 8,'2017-01-01'),
(102,2, 7,'2017-01-01'),
(101,1,10,'2018-01-01'),
(101,2,10,'2018-01-01'),
(102,1,10,'2018-01-01'),
(102,2,10,'2018-01-01');

SELECT x.student
     , SUM(x.score) total 
  FROM my_table x
  JOIN 
     ( SELECT student
            , question_id
            , MAX(answered_on) answered_on 
         FROM my_table 
           -- OPTIONAL WHERE CLAUSE HERE 
        GROUP 
           BY student
            , question_id
     ) y 
    ON y.student = x.student 
   AND y.question_id = x.question_id 
   AND y.answered_on = x.answered_on 
 GROUP 
    BY student;

+---------+-------+
| student | total |
+---------+-------+
|     101 |    20 |
|     102 |    20 |
+---------+-------+