在子查询中使用MAX等计算值

时间:2013-03-11 21:57:38

标签: mysql

我有以下MySQL表(student_lesson_progress):

  • Id
  • lessonId
  • studentId
  • lessonStatusTypeId
  • recordDateTime
  • ...

我需要记录当前学年的学生人数,他们的最后状态是两个值(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  

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

2 个答案:

答案 0 :(得分:0)

您似乎错过了M1M2

之间的联接
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

答案 1 :(得分: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)