Joining to MAX date record in group

前端 未结 3 1739
耶瑟儿~
耶瑟儿~ 2020-12-14 06:06
Job
--------
Id
Description


JobStatus
----------
Id
JobId
StatusTypeId
Date

How do I get the current JobStatus for all jobs?

3条回答
  •  时光说笑
    2020-12-14 06:59

    One way is this:

    SELECT j.*, s2.StatusTypeId, s2.Date
    FROM Job j
        JOIN
        (
            SELECT JobId, MAX(Date) AS LatestStatusDate
            FROM JobStatus 
            GROUP BY JobId
        ) s1 ON j.JobId = s1.JobId
        JOIN JobStatus s2 ON s1.JobId = s2.JobId AND s1.LatestStatusDate = s2.Date
    

    Assuming you won't have 2 rows in JobStatus for the same JobId + Date combination

提交回复
热议问题