Solved

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

Posted on 2010-09-05
6
618 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
Backup Your Microsoft Windows Server®

Backup all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

 
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

Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

Question has a verified solution.

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

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 backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

920 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

17 Experts available now in Live!

Get 1:1 Help Now