Link to home
Start Free TrialLog in
Avatar of cbridgman
cbridgmanFlag for United States of America

asked on

SQL Query that Returns the Next Most Recent Record

I'm trying to write an SQL script to find the next to last record added to a table. The table in question (it's a table that tracks status changes to records that are in another table) has one row for every status change that is made to a record that is in the other table. So, there is a one to many relationship between the two tables. Also, every row in the status change table is date and time stamped.

For the sake of simplicity, let's call the status change table "TBL_B" and its "parent" table we can call "TBL_A". The 2 tables are related to one another through a single column (TBL_A.PONUM and TBL_B.PONUM).

What I am looking for is not the most recent record that was added to TBL_B for every record that is in TBL_A, but the next most recent. For example, assume that TBL_B has 4 rows in it for a single row in TBL_A as follows:

Row 1 was added on 1/1/2018
Row 2 was added on 2/1/2018
Row 3 was added on 3/1/2018
Row 4 was added on 4/1/2018

I want my query to return only Row 3

This is for a SQL Server DB

Any ideas / assistance / guidance is much appreciated
Avatar of _agx_
_agx_
Flag of United States of America image

Edit: Added tested example - You should be able to use an OUTER JOIN and ROW_NUMBER() to order the results by the date in DESC order. Then grab records for the second row only.


create table tbl_a (
  PoNum varchar(50)
)  
create table tbl_b (
  PoNum varchar(50)
  , DateAdded datetime
)  

insert into tbl_a values ('PO-A');
insert into tbl_b values
('PO-A', '4/1/2018')
,('PO-A', '3/1/2018')
,('PO-A', '2/1/2018')
,('PO-A', '1/1/2018')
;


;WITH data AS
(
SELECT a.PoNum
       , b.DateAdded
	   , ROW_NUMBER() OVER(PARTITION BY a.PoNum ORDER BY a.PoNum, b.DateAdded DESC) AS Row
FROM   TBL_A a LEFT JOIN TBL_B b ON a.PONum = b.PONum
)
SELECT * 
FROM   data
WHERE  Row = 2
;

Open in new window

Avatar of cbridgman

ASKER

The 2nd select statement is failing on an invalid object name "data". Is that the correct name or should I replace data with some other value?

Also, I am guessing that somecolumn and dataadded are from table B. Is that correct?
ASKER CERTIFIED SOLUTION
Avatar of _agx_
_agx_
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Oh, wait a second. I excluded the ;WITH data AS piece by mistake. It appears that it ran when I added it in. Still have some testing to do though to ensure that it is returning the correct records. I will let you know.
It appears that the query is returning the correct results now. Thanks very much for your help
Running the SQL script that was suggested above