Solved

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

Posted on 2010-09-05
6
621 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
ID: 33606374
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
ID: 33606392
select top 1 a.* from
(
  Select top 2 *
  from orders
) a
order by a.OrderDate desc
0
 

Author Comment

by:FaheemAhmadGul
ID: 33606446
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
Use Case: Protecting a Hybrid Cloud Infrastructure

Microsoft Azure is rapidly becoming the norm in dynamic IT environments. This document describes the challenges that organizations face when protecting data in a hybrid cloud IT environment and presents a use case to demonstrate how Acronis Backup protects all data.

 
LVL 23

Accepted Solution

by:
Rajkumar Gs earned 150 total points
ID: 33606456

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
ID: 33606506
Many thanks. I am very grateful. Regards
0
 
LVL 23

Expert Comment

by:Rajkumar Gs
ID: 33606509
I love to hear, you got your solution :)

All the best
Raj
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
Via a live example, show how to setup several different housekeeping processes for a SQL Server.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

770 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