I have a table with many records and I want to know only the record which I have created at second last.
For ex: I have a table customer
in which customerID
are random numbers.
Now I want to select second last row.
customerID customer_name cont_no
---------------------------------------
7 david sam 5284
1 shinthol 1
11 lava 12548
2 thomas 1
3 peeter 1
4 magge 1
5 revas 1
6 leela 123975
Output row :
customerID customer_name cont_no
5 revas 1
I don't want second highest...
I want second last row.
Try this
Here
RowNum
is a column by numbering the rows in the table with out ordering it.max(RowNum) - 1
will give the second lastPosting as an answer as it is a big comment
David: ok i will do it next time but what i can do now for this problem there are many recods in thousand.is there any way to do this?? @Deepanshu Kalara
Me: @david sam, I dont think there is a way to do this now. Best bet would be copy those thousand records in excel and hope that they are in order you inserted them. Create a manual column there like you would have had if you had auto-increment. and correct your table structure by inserting that column in the table itself, as you said you would.
i know this is too late but you can try this.
I would recommend to add an extra field in your table id with
autoincrement
.Its not a big deal as below :
Query :
Output :
select identity(int,1,1) as Id, * into #temp from customer
select * from #temp where Id = (select max(Id) as count from #temp group by Id) - 1 drop table #temp
With SQL Server 2012 or higher you can do it in one line code: