Skip to content
Advertisement

SQL Query to get 2nd most recent results with multiple columns

I am trying to obtain the 2nd most recent results for all distinct part_id’s(based off of order_date) to go into a report I am working on making to compare it to the most recent results.

The commented sections are from another approach I was trying but unsuccessful with.

Any help is greatly appreciated!

(Side note: I am new to posting on SO, and I apologize in advance if this is answered elsewhere, but I was unable to find anything that pertained to this issue)

I am using the following query:

EDIT 5/28 LATE NIGHT:

Lets say below is the data set I need the 2nd result from each part_id (2nd based off of ORDER_DATE DESC)

I am looking to receive the following output (for more than 3 different part id’s):

There are also additional columns in the query but formatting them as a table would have taken much longer. I have left off a few of the columns on the examples.

ANOTHER EDIT

I am not sure if this information helps, but I am trying to compare the most recent results to the previous results to show pricing and vendor differences. We are compiling the data into Report Builder; My approach here was to create 2 separate datasets one with the most recent and the other with the 2nd most recent and combine the data from the datasets in Report Builder. If there is an easier approach and I am heading in the wrong direction please let me know!

Example:

EDIT THE NEXT MORNING

Thanks everyone for all the help! After Harry posted his solution I went ahead and made some tiny edits to get the columns I needed added on. I swapped his union portion with the original select statement. Everything here seems to be exactly what I am looking for!

Code:

Advertisement

Answer

Based on the data you have provided, you can do this with a cte and row number function.

Note – it always helps to show the whole picture rather than just ask for the part you want help with (usually).. as it is easier to answer if we can understand the entire issue!

See code below

result

Result

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement