我觉得这应该很容易做,我只是在某个地方犯了一些小错误。大概应该补充说我是老师而不是编码员,所以我不熟悉SQL。另外,我在这里看到了一堆问题,但都没有工作。为每个条目选择最近的答案MySQL
我有表student_answers(id, student_id, question_id, answer, result, date_time)
我想获得一个学生对每个问题输入的最后答案question_id
,answer
,result
和date_time
。所以如果他们回答三次问题7,我只想看到他们输入的最后answer
和result
。
出于教学目的,我不能简单地更新每一行,因为他们重新输入答案。
我尝试以下查询
SELECT id, question_id, answer, result, date FROM Student_Answers
WHERE student_id = 505 AND question_id in (select id from Test_Questions q where q.test_id = 37)
Group by question_id
having date = max(date)
ORDER BY Student_Answers`.`question_id` ASC
但不包括与多个答案的问题在所有,只有我,学生505回答一次问题。学生505回答问题3和4两次,剩下的只有一次,我只看到了结果1,2和5
我尝试这个查询
SELECT
b.*
FROM
(
SELECT question_id, MAX(date) AS maxdate
FROM TP_Student_Answers
GROUP BY question_id
) a
INNER JOIN
TP_Student_Answers b ON
a.question_id = b.question_id AND
a.maxdate = b.date
and b.student_id = 505
and b.question_id in (select id from TP_Questions q where q.test_id = 37)
ORDER BY
b.question_id
但是这对只给了我3和4没有一次他只尝试过一次。任何帮助将不胜感激!
这是数据的一个样本:
id student_id question_id answer result date
7133 505 1 a correct 2012-11-16 09:03:58
7134 505 2 c wrong 2012-11-16 09:03:58
7135 505 3 e wrong 2012-11-16 09:03:58
7136 505 3 d wrong 2013-12-16 09:03:58
7137 505 4 c correct 2012-11-16 09:03:58
7138 505 4 d wrong 2013-12-16 09:03:58
7139 505 5 blank 2012-11-16 09:03:58
当我运行查询我想看看:
7133 505 1 a correct 2012-11-16 09:03:58
7134 505 2 c wrong 2012-11-16 09:03:58
7136 505 3 d wrong 2013-12-16 09:03:58
7138 505 4 d wrong 2013-12-16 09:03:58
7139 505 5 blank 2012-11-16 09:03:58
通知条目7135和7137被省略,因为还有更晚的答案对于其中的每一个问题
你可以分享更好的解决方案的样本数据(记录)。 – SparKot 2013-03-13 07:11:09
您的示例数据似乎缺少足够的信息,您是否也可以提供期望的结果? – 2013-03-13 07:43:56