Home > Software engineering >  How can i take most recent date with where clause
How can i take most recent date with where clause

Time:01-03

There are some distinct columns on my student_list_history table. So i'm trying to take most recent date for those distinct columns. There is a create_date row so i will use it for that. I tried to add where create_date=MAX(create_date) but it didn't work. Any clue?

update student_list liste  
    set last_approver_id=( select LAW_CREATED_ID from student_list_history hist
     where liste.id=hist.list_id and new_status='3'  )
where ( liste.status='5' or liste.status='3' );  

CodePudding user response:

That would be a subquery:

SELECT LAW_CREATED_ID
  FROM student_list_history hist
 WHERE     liste.id = hist.list_id
       AND hist.new_status = '3'
       AND hist.create_date = (SELECT MAX (b.create_date)
                               FROM student_list_history b
                               WHERE b.student_id = hist.student_id  --> ???
                              )

??? marks condition I'm not sure about because I don't know what that table contains; I presume you need the most recent date for a student (so I used student_id to join tables). You should know what to put here.

CodePudding user response:

You can use a MERGE statement and MAX(...) KEEP (DENSE_RANK LAST ORDER BY ...) aggregation function to get the maximum value for the the maximum of another column:

MERGE INTO student_list l
USING (
  SELECT list_id,
         MAX(LAW_CREATED_ID) KEEP (DENSE_RANK LAST ORDER BY create_date)
           AS law_created_id
  FROM   student_list_history
  WHERE  new_status='3'
  GROUP BY list_id
) h
ON (h.list_id = l.id AND l.status IN ('3', '5'))
WHEN MATCHED THEN
SET last_approver_id=h.law_created_id;
  • Related