简体   繁体   中英

How can i take most recent date with where clause

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' );  

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM