Solved

SQL Query to Get the 2nd Last Record from an SQL Database Table

Posted on 2010-09-05
6
615 Views
Last Modified: 2013-12-25
I need help with an SQL Query to get Data from an SQL Server Databas. I need an SQL query which would get the 2nd last record from a table.
To explain this further if the table I need to pull data from looks like the following:

Table Name: Orders
OrderID      OrderDate      Item
1            02/09/2010      Apple
2            04/09/2010      Mango
3            05/09/2010      Orange
4            06/09/2010      Bannana

I would like my MyQuery to get me the 2nd last record that is with OrderID 3. The following query gets me the last (most recently saved record that is the one with OrderID 4 from the Orders Table.

MyQuery = "SELECT TOP 1 * FROM Orders"

I would like a modification of the above query that would get me the record with OrderID3.

I    WOULD ALSO LIKE     a modification of this query that would get me the 3rd last Record (that is the record with RecordID 2 from the this table.

Many thanks for your help. Please note I am using Visual Studio 2008


0
Comment
Question by:FaheemAhmadGul
  • 3
  • 2
6 Comments
 
LVL 23

Expert Comment

by:Rajkumar Gs
Comment Utility
If your MS SQL Server database version is 2005 or higher, ROW_NUMBER() function will help you to achieve your requirement like this

row_no = 2 means last 2nd record. Modify this parameter according to your requirement.

Raj
select * from

(

select *, row_number() over(order by OrderID desc) row_no

from table

) a 

where row_no = 2

Open in new window

0
 
LVL 1

Expert Comment

by:z_alex
Comment Utility
select top 1 a.* from
(
  Select top 2 *
  from orders
) a
order by a.OrderDate desc
0
 

Author Comment

by:FaheemAhmadGul
Comment Utility
Thank you for your comment on my request for help. Unfortunately, being  a beginner,  I have not been able to follow the solution. The exact function in which I need to put this query is as follows:

I would be grateful, if you could modify the query in the code exactly as I should put it in this function. Please note that I am sorting the Table but a Field AutoDate and I wish to get the 2nd last record ffrom this table. Please note that I am using Visual Basic and the Database is SQL Server 2005 Express Edition.

Public Function getOrder(ByVal ClientNamesID As Integer) As DataTable

        Try
            cmdSelect = New SqlClient.SqlCommand
            cmdSelect.Connection = conn

            query = "SELECT TOP 1 Item FROM Orders WHERE ClientNamesID =" & ClientNamesID & " ORDER BY AutoDate DESC"
           

            conn.Open()


            Return dc.executeQuery(query, cmdSelect, conn)

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            If Not conn.State = ConnectionState.Closed Then conn.Close()
        End Try
    End Function
Public Function getOrder(ByVal ClientNamesID As Integer) As DataTable

        Try
            cmdSelect = New SqlClient.SqlCommand
            cmdSelect.Connection = conn

            query = "SELECT TOP 1 Item FROM Orders WHERE ClientNamesID =" & ClientNamesID & " ORDER BY AutoDate DESC"
            

            conn.Open()


            Return dc.executeQuery(query, cmdSelect, conn)

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            If Not conn.State = ConnectionState.Closed Then conn.Close()
        End Try
    End Function

Open in new window

0
Get up to 2TB FREE CLOUD per backup license!

An exclusive Black Friday offer just for Expert Exchange audience! Buy any of our top-rated backup solutions & get up to 2TB free cloud per system! Perform local & cloud backup in the same step, and restore instantly—anytime, anywhere. Grab this deal now before it disappears!

 
LVL 23

Accepted Solution

by:
Rajkumar Gs earned 150 total points
Comment Utility

Public Function getOrder(ByVal ClientNamesID As Integer) As DataTable



        Try

            cmdSelect = New SqlClient.SqlCommand

            cmdSelect.Connection = conn



--            query = "SELECT TOP 1 Item FROM Orders WHERE ClientNamesID =" & ClientNamesID & " ORDER BY AutoDate DESC"



			query = "select * from (select *, row_number() over(order by OrderID desc) row_no " & _

				" from Orders where ClientNamesID =" & ClientNamesID & ") a where row_no = 2"

            



            conn.Open()





            Return dc.executeQuery(query, cmdSelect, conn)



        Catch ex As Exception

            MessageBox.Show(ex.Message)

        Finally

            If Not conn.State = ConnectionState.Closed Then conn.Close()

        End Try

    End Function

Open in new window

0
 

Author Closing Comment

by:FaheemAhmadGul
Comment Utility
Many thanks. I am very grateful. Regards
0
 
LVL 23

Expert Comment

by:Rajkumar Gs
Comment Utility
I love to hear, you got your solution :)

All the best
Raj
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

I was working on a PowerPoint add-in the other day and a client asked me "can you implement a feature which processes a chart when it's pasted into a slide from another deck?". It got me wondering how to hook into built-in ribbon events in Office.
This article describes how to use the timestamp of existing data in a database to allow Tableau to calculate the prior work day instead of relying on case statements or if statements to calculate the days of the week.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now