mysql - 添加最新结果

标签 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      |
+---------+-------------+

最佳答案

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

关于mysql - 添加最新结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49435186/

相关文章:

sql - SQL Oracle 中的减查询

C程序打印给定数字的数字平方和?

mysql - 用重复字段的总和更新 table1 的列

php - 有没有比附加 sql 字符串更好的方法来生成条件 sql?

php - 限制表单输入尝试

php - 如何组织一组模块化 div 以齐平

php - 小组结果分组

excel - 数据透视表中平均列的总和

设置 IF NULL 或其他值的 MySQL 更新字段

php - AWS MySQL 是否缓存数据?拉拉维尔 5