If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

 
Go Back  dBforums > Database Server Software > Oracle > How to select latest date record

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 12-28-11, 03:56
boybles boybles is offline
Registered User
 
Join Date: Mar 2004
Posts: 7
Question How to select latest date record

I'm trying to select the latest record before the provided date. For example, in the following scenario, I have a Tickets table:

Tickets
------------
TicketID (NUMBER 3,PK)
TicketDate (DATE)
EventName (VC2 50)

Example Data:
TicketID|TicketDate|Eventname
========================
1|1/3/2011|Concert A
2|5/4/2011|Concert B
3|6/3/2011|Concert C
4|7/5/2011|Concert D

In the above table, if I have a date of 6/1/2011, how do I select the latest record before that date (in this case, it would be TicketID=2)?

Thanks,
Tony
Reply With Quote
  #2 (permalink)  
Old 12-28-11, 05:45
Littlefoot Littlefoot is offline
Lost Boy
 
Join Date: Jan 2004
Location: Croatia, Europe
Posts: 3,629
Code:
SQL> select t.eventname
  2  from tickets t
  3  where t.ticketdate = (select max(t1.ticketdate)
  4                        from tickets t1
  5                        where t1.ticketdate < to_date('6/1/2011', 'mm/dd/yyyy')
  6                       );

EVENTNAME
--------------------------------------------------
Concert B

SQL>
Reply With Quote
  #3 (permalink)  
Old 12-28-11, 08:02
shammat shammat is offline
Registered User
 
Join Date: Nov 2003
Posts: 2,408
If the table is large, using a window (aka analytical) function might be faster, because only a single scan is required:
Code:
select TicketID, 
       TicketDate, 
       EventName 
from (
    select TicketID, 
           TicketDate, 
           EventName, 
           dense_rank() over (order by TicketDate desc) as rnk
    from tickets
    where ticketdate < to_date('6/1/2011', 'mm/dd/yyyy')
) t
where rnk = 1;
Reply With Quote
  #4 (permalink)  
Old 01-01-12, 18:05
boybles boybles is offline
Registered User
 
Join Date: Mar 2004
Posts: 7
Smile Thank you

Thank you guys. Both solutions worked beautifully.
Tony
Reply With Quote
Reply

Tags
date, previous, select

Thread Tools Search this Thread
Search this Thread:

Advanced Search
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

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On