Unix Technical Forum

Select statement for last and secondlast value

This is a discussion on Select statement for last and secondlast value within the SQL Server forums, part of the Microsoft SQL Server category; --> Assume I have a table like: CustomerName OrderDate OrderPartID London 7/7/99 33 Paris 7/6/99 22 Rome 7/5/99 22 London ...


Go Back   Unix Technical Forum > Database Server Software > Microsoft SQL Server > SQL Server

FAQ Members List Calendar Search Today's Posts Mark Forums Read
  #1 (permalink)  
Old 02-29-2008, 09:49 AM
gerald
 
Posts: n/a
Default Select statement for last and secondlast value

Assume I have a table like:

CustomerName OrderDate OrderPartID
London 7/7/99 33
Paris 7/6/99 22
Rome 7/5/99 22
London 6/3/99 44
Paris 6/4/99 11
Rome 6/20/99 99
London 4/3/99 12
Paris 4/4/99 13
Rome 4/20/99 94

I a looking of a single SQL statement which will find the last and
second last order from customer "London" in a way like

CustomerName LastOrderDate SecondLastOrderDate
London 7/7/99 6/3/99

Can anyone help me?

Gerald

Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #2 (permalink)  
Old 02-29-2008, 09:49 AM
Simon Hayes
 
Posts: n/a
Default Re: Select statement for last and secondlast value

Something like this might work (but you need to consider what to do if
there are multiple orders on the same date):

select
'London',
max(dt.orderdate) as 'LastOrder',
min(dt.orderdate) as 'SecondLastOrder'
from
(
select top 2 orderdate
from dbo.orders
where customername = 'London'
order by orderdate desc
) dt

Simon

Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump


All times are GMT. The time now is 02:03 PM.


Powered by vBulletin® Version 3.6.5
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
SEO by vBSEO 3.2.0
www.UnixAdminTalk.com