我有这张桌子:
ID STUDENT CLASS QUESTION ANSWER TIME
1 1 1 1 c 12:30
2 1 1 1 d 12:36
3 1 1 2 a 12:38
4 2 1 1 b 11:24
5 2 1 1 c 11:26
6 2 1 3 d 11:35
7 2 3 3 b 11:24
我正在尝试编写一个执行此操作的查询:
对于特定CLASS中的每个学生,请为每个问题选择最新的答案。
因此,选择类“1”将返回:
ID STUDENT CLASS QUESTION ANSWER TIME
2 1 1 1 d 12:36
3 1 1 2 a 12:38
5 2 1 1 c 11:26
6 2 1 3 d 11:35
我尝试了各种子查询,联接和分组组合,但没有任何工作。有什么想法吗?
答案 0 :(得分:0)
您可以使用子查询获取最新ANSWER
每QUESTION
,然后将其用作派生表并重新连接到原始表:
SELECT m.*
FROM mytable AS m
INNER JOIN (
SELECT STUDENT, QUESTION, MAX(`TIME`) AS mTime
FROM mytable
WHERE CLASS = 1
GROUP BY STUDENT, QUESTION
) AS d ON m.STUDENT = d.STUDENT AND m.QUESTION = d.QUESTION AND m.`TIME` = d.mTime
WHERE m.CLASS = 1