加入到组中的MAX日期记录

时间:2011-01-31 14:22:36

标签: sql-server tsql

Job
--------
Id
Description


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

如何获取所有工作的当前JobStatus

等等......

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

(我确信已经有很多类似的问题,但我找不到任何我需要的东西。)

3 个答案:

答案 0 :(得分:43)

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

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
        )

这些查询正确处理Date上的可能重复项。

答案 1 :(得分:7)

一种方法是:

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

假设您在JobStatus中没有2行用于相同的JobId +日期组合

答案 2 :(得分:3)

SQL Server 2000的另一种(效率不高,但易于理解)解决方案: -

SELECT  *
FROM    job j
WHERE   j.date = (SELECT MAX(date) 
                  FROM   job 
                  WHERE  id = j.id)