45
Job
--------
Id
Description


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

How do I get the current JobStatus for all jobs?

so something like....

SELECT * FROM Job j
INNER JOIN ( /* Select rows with MAX(Date) grouped by JobId */ ) s
    ON j.Id = s.JobId

(I'm sure there are a bunch of similar questions already but I couldn't find anything which exactly does what I need).

fearofawhackplanet
  • 52,166
  • 53
  • 160
  • 253
  • Possible duplicate of [T-SQL Subquery Max(Date) and Joins](http://stackoverflow.com/questions/879111/t-sql-subquery-maxdate-and-joins) – KyleMit Jul 27 '16 at 17:28

3 Answers3

76

In SQL Server 2005+:

SELECT  *
FROM    job j
OUTER APPLY
        (
        SELECT  TOP 1 *
        FROM    jobstatus js
        WHERE   js.jobid = j.jobid
        ORDER BY
                js.date DESC
        ) js

In SQL Server 2000:

SELECT  *
FROM    job j
LEFT JOIN
        jobstatus js
ON      js.id =
        (
        SELECT  TOP 1 id
        FROM    jobstatus jsi
        WHERE   jsi.jobid = j.jobid
        ORDER BY
                jsi.date DESC
        )

These queries handle possible duplicates on Date correctly.

Quassnoi
  • 413,100
  • 91
  • 616
  • 614
10

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

AdaTheDev
  • 142,592
  • 28
  • 206
  • 200
  • I know I'm not supposed to thank you. But this is really excellent. Essentially what's happening here is that you're trusting that the highest date connected to that job will be matched to the second more important join. – Zei Sep 29 '20 at 02:41
5

Another (not very efficient, but easy to understand) solution for SQL Server 2000:--

SELECT  *
FROM    job j
WHERE   j.date = (SELECT MAX(date) 
                  FROM   job 
                  WHERE  id = j.id)
David
  • 51
  • 1
  • 2