Joh*_*ohn 2 mysql sql greatest-n-per-group
我有一张桌子可以跟踪课程的出勤情况.列是课程,课程,人格和日期.我有一个查询(下面),它提取一个人出现的最早日期以及相关的课程,课程和人格.这用于确定一个人何时开始特定课程并确保他们从第一课开始.这工作正常,但我遇到的问题是每个课程运行此查询.例如,找到特定课程中每个人的第一个日期,而不是每个课程.现在我只是运行更通用的查询并在biz层中过滤它.
我混淆了这一点,原谅任何错别字:
select a.courseid,
a.lesson,
a.personid,
a.thedate
from (select personid,
min(thedate) as earliestdate
from attendance
group by personid) as x
inner join attendance as a on (a.personid = x.personid and a.thedate = x.thedate)
Run Code Online (Sandbox Code Playgroud)
只需将person_id分组,当然在内部查询中:
select a.courseid, a.lesson, a.personid, a.thedate
from (
select personid, courseid, min(thedate) as earliestdate
from attendance
group by personid, courseid
) as x
inner join attendance as a
on (a.personid = x.personid and
a.thedate = x.thedate and
a.courseid=x.course_id)
Run Code Online (Sandbox Code Playgroud)