Solved

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

Posted on 2010-09-05
6
623 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

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

Question has a verified solution.

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

I have a large data set and a SSIS package. How can I load this file in multi threading?
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…
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…

821 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