0

我有以下 MySQL 表(student_lesson_progress):

  • ID
  • 课程编号
  • 学生卡
  • 课程状态类型 ID
  • 记录日期时间
  • ...

我需要捕获当前学年中最后状态为两个值(6 或 13)之一的学生数量。

我是 SQL 新手。我想我想从获取每个 studentId/lessonId 组合的最后一条记录开始。然后我想将该列表缩小到符合我标准的列表。这是我认为我想要的查询,但它在子查询中的“Max”处触发语法错误。

SELECT M1.*  
FROM student_lesson_progress M1  
{  
SELECT MAX(id) as lastRecord, lessonId, studentId, lessonStatusTypeId  
FROM student_lesson_progress  
GROUP BY studentId, lessonId  
} M2  
WHERE recordDateTime > "2012-08-01" 
AND (lessonStatusTypeId = 13 or lessonStatusTypeId = 6)  
ORDER BY studentId, lessonId, lastRecord  

我很难找到具有计算值的子查询的语法示例。建议?或者也许有更好的方法?

4

2 回答 2

0

如果 ID 一直在增加,您可以使用以下查询:

SELECT COUNT(*)
FROM student_lesson_progress
WHERE
  id IN (SELECT max(id)
         FROM student_lesson_progress
         GROUP BY studentId, lessonId)
  AND recordDateTime > '2012-08-01'
  AND lessonStatusTypeId IN (13, 6)
于 2013-03-11T22:11:55.823 回答
0

看来您只是缺少和之间的M1连接M2

SELECT COUNT(M1.StudentID) AS Students
FROM student_lesson_progress M1
    INNER JOIN
    (SELECT MAX(id) as lastRecord, lessonId, studentId, lessonStatusTypeId  
     FROM student_lesson_progress  
     GROUP BY studentId, lessonId) M2 ON M1.ID = M2.lastRecord -- need to join M1 and M2 together
WHERE recordDateTime > '2012-08-01'
AND (lessonStatusTypeId = 13 or lessonStatusTypeId = 6)
ORDER BY studentId, lessonId, lastRecord
于 2013-03-11T22:01:54.183 回答