cbridgman
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
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
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?
Also, I am guessing that somecolumn and dataadded are from table B. Is that correct?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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.
ASKER
It appears that the query is returning the correct results now. Thanks very much for your help
ASKER
Running the SQL script that was suggested above
Open in new window