Home > Software engineering >  get most recent row
get most recent row

Time:05-31

tables :

task : id(bigint) name (varchar). holds task details

job : id(varchar(UUID)) task_id(bigint (id of class)),staus(varchar(50)),created_time(time stamp). hold task execution details

possible values for status are FAIL/COMPLETED/INTERRUPTED

what i am trying to achieve is to get all the most recent values for each and every task from the job table

if job is not present for a task then return status as null

SELECT
    p.id, j.status
FROM
    tas p
        inner JOIN
            job j ON j.task_id = p.id
        inner JOIN
    job j1 ON j.task_id = j1.task_id and j.create_time > j1.create_time;

CodePudding user response:

For SQL versions that support ROW_NUMBER() you could do:

WITH info as(
  SELECT
    p.id, 
    j.status,
    ROW_NUMBER() OVER(PARTITION BY p.id ORDER BY j.created_time DESC) AS rn
  FROM tas p
  LEFT JOIN job j ON j.task_id = p.id
)
SELECT id, status
FROM info
WHERE rn = 1

Otherwise, just use a cte or sub-query.

SELECT p.id, t.status
FROM tas AS p
LEFT JOIN (
  SELECT task_id, MAX(created_time) as created_time
  FROM job
  GROUP BY task_id
) as lt
ON p.id = lt.task_id
LEFT JOIN task AS t ON lt.task_id = t.task_id AND lt.created_time = t.created_time

  • Related