how to retrive last two record from table.

Posted by Johnbrother49 under Sql Server on 7/22/2012 | Points: 10 | Views : 1214 | Status : [Member] | Replies : 7
H
I want to retrive last two record from this table.How can i do it?

id city state
18 Jaipur Rajasthan
38 Mumbai Maharashtra
22 Ahmedabad Gujarat
21 Surat Gujarat
25 Pune Maharashtra
19 asd asd

Outpu Should be..
25 Pune Maharashtra
19 asd asd
thanks in advance




Responses

Posted by: prashant12-7256 on: 7/22/2012 [Member] Starter | Points: 25

Up
0
Down

To retrive last 2 records use top function and order by descending

Like this :

Select  Top 2 *  from tablename ORDER BY id DESC;


Johnbrother49, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Pandians on: 7/23/2012 [Member] [MVP] Silver | Points: 25

Up
0
Down
If you don't have any column as sequence order then, you have to do some workaround like
select Identity(Int,1,1) [Seq],* Into #Sorted from <TableName>


Select ID, City, [State] from
(
Select Top 2 * from #Sorted Order By Seq Desc
)as x Order by Seq

Drop Table #Sorted
In your sample record, "ID" column data is not sequential order!

Cheers
www.SQLServerbuddy.blogspot.com
iLink Multitech Solutions

Johnbrother49, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: CGN007 on: 7/23/2012 [Member] Silver | Points: 25

Up
0
Down
Please refer this link
http://www.dotnetfunda.com/forums/thread9456-how-to-select-the-last-three-value-in-database.aspx

Johnbrother49, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Dotnetrajanikanth on: 7/23/2012 [Member] Starter | Points: 25

Up
0
Down
http://www.sqlservercurry.com/2009/02/retrieve-last-n-rows-based-on-condition.html

____________
www.flickr.com/photos/psdesigner/

Johnbrother49, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Dotnetrajanikanth on: 7/23/2012 [Member] Starter | Points: 25

Up
0
Down
Johnbrother49,

Can we use orderby statement in this or do you want the results without the main table being sorted??

____________
www.flickr.com/photos/psdesigner/

Johnbrother49, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: Oswaldlily on: 7/23/2012 [Member] Starter | Points: 25

Up
0
Down
select top 2 * from tablename order by id desc

Johnbrother49, if this helps please login to Mark As Answer. | Alert Moderator

Posted by: CGN007 on: 7/31/2012 [Member] Silver | Points: 25

Up
0
Down
Mark as answer if it helps...,That motivates...!!!

Johnbrother49, if this helps please login to Mark As Answer. | Alert Moderator

Login to post response