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 > DB2 > Grouping

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 03-30-04, 11:48
nbozic nbozic is offline
Registered User
 
Join Date: Mar 2004
Posts: 51
Question Grouping

Hi,

I tried many times but I couldn't come up with a query that will yield records of the most recent date for each ID.

The starting table TBL_DATE that I will use in the query, for example:
___________
ID | Date
------------
01 | 12/01
01 | 12/05
02 | 12/08
03 | 12/10
03 | 12/11
03 | 12/16
___________

The desired recordset returned (most recent date for each ID):

___________
ID | Date
------------
01 | 12/05
02 | 12/08
03 | 12/16
___________


I tried different techniques using GROUP BY and MAX(), but nothing worked so far... Any ideas?

Thanks,

NB
Reply With Quote
  #2 (permalink)  
Old 03-30-04, 12:10
Damian Ibbotson Damian Ibbotson is offline
Padawan
 
Join Date: Jun 2002
Location: UK
Posts: 525
This is one way...
Code:
select id
,        date
from  (
          select id
           ,        date
           ,        rank() over (partition by id order by date desc nulls last) rank
           from  tbl_date
         ) ranked_dates
where rank = 1
;
Reply With Quote
  #3 (permalink)  
Old 03-30-04, 12:11
Marcus_A Marcus_A is offline
Registered User
 
Join Date: May 2003
Location: USA
Posts: 5,198
select distinct(ID), DATE_COL from TBL_DATE A
where DATE_COL in
(select max(DATE_COL) from TBL_DATE B
where A.ID = B.ID)
__________________
M. A. Feldman
IBM Certified DBA on DB2 for Linux, UNIX, and Windows
IBM Certified DBA on DB2 for z/OS and OS/390
Reply With Quote
  #4 (permalink)  
Old 03-30-04, 12:15
nbozic nbozic is offline
Registered User
 
Join Date: Mar 2004
Posts: 51
Thanks guys, I'll try it out!
Reply With Quote
Reply

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