简体   繁体   中英

How can I find most recently changed row?

I have a table which contains audit related records. There is a column which stores the approval status with value 'N' and 'Y'. I have to find the record which was recently changed from approve status 'Y' to 'N'.

Sample data:

Request_No    approve_status request_create_date          audit_no_in
22866         N              2016-06-21 11:47:12.7530000  1016
22866         N              2016-06-21 11:46:52.3660000  1015
22866         Y              2016-06-21 11:46:13.9290000  1014
22866         Y              2016-06-21 11:45:14.3200000  1013
22866         N              2016-06-21 11:37:27.9410000  1012
22866         Y              2016-06-21 11:37:03.4510000  1011
22866         N              2016-06-21 11:32:29.6310000  1010
22866         Y              2016-06-21 11:31:41.0270000  1009
22866         N              2016-06-20 19:17:30.4820000  1008
22866         N              2016-06-20 19:14:30.4720000  1007
22866         Y              2016-06-02 13:12:53.5170000  1006

Required output:

Request_No    approve_status request_create_date          audit_no_in
22866         N              2016-06-21 11:46:52.3660000  1015

Any help would be greatly appreciated.

You can use LEAD() and ROW_NUMBER() together:

SELECT p.request_no,p.approve_status,p.request_create_date,p.audit_no_in
FROM(
    SELECT s.*,
           ROW_NUMBER() OVER(PARTITION BY s.request_no ORDER BY s.request_create_date DESC) as rnk
    FROM ( 
        SELECT t.*,
               LEAD(t.approve_status,1,0) OVER(PARTITION BY t.request_no ORDER BY t.request_create_date DESC) as last_status
        FROM YourTable t) s
    WHERE s.approve_status = 'Y' AND s.last_status = 'N') p
WHERE p.rnk = 1

The first inner query select the last status, the second one filter those who didn't change from Y to N and ranks them base on their dates, the third one filter only the newest change.

I use another way to find the result you want. Just search a recently 'Y' record where has a 'N' record updated. Also, if your database engine version is 2008, it still can process.

SQL :

select * from Table1 where audit_no_in = (
select Max(audit_no_in) + 1 
from Table1 
where approve_status ='Y' 
and audit_no_in < (select max(audit_no_in) from Table1 where approve_status ='N'))

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