Select property from max in cross apply SQL

557 views Asked by At

I currently have this query

SELECT
  OC.*,
  NEW.LAST_JOB_RUN_DATE
FROM dbo.CUBES OC
CROSS APPLY (SELECT
  MAX(LAST_END_RUN_DATE) AS LAST_JOB_RUN_DATE
FROM dbo.JOBS OJ
WHERE OJ.CUBE_ID = OC.ID) NEW

Each CUBE can have multiple JOBS. I want this query to return me all the cubes, along with the last time the latest job was run. This works fine. Now i also want to add the STATUS of that job too, but i can't seem to get the query working. The query above works but doesn't return me the status associated with it, which is what i want.
Is there a way to change the above query to also return the STATUS of the job containing the MAX(LAST_END_RUN_DATE) ?

1

There are 1 answers

6
DVT On BEST ANSWER
SELECT
  OC.*,
  NEW.LAST_JOB_RUN_DATE,
  NEW.STATUS
FROM dbo.CUBES OC
OUTER APPLY (SELECT TOP (1) OJ.LAST_END_RUN_DATE AS LAST_JOB_RUN_DATE, OJ.STATUS
FROM dbo.JOBS OJ
WHERE OJ.CUBE_ID = OC.ID
ORDER BY OJ.LAST_END_RUN_DATE DESC ) NEW