Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find most recently changed row?

Tags:

sql

sql-server

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.

like image 717
java_maestros Avatar asked Jun 21 '16 07:06

java_maestros


1 Answers

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.

like image 98
sagi Avatar answered Oct 13 '22 08:10

sagi