Kyle McIntire
Kyle McIntire

Reputation: 15

SQL select greater date when comparing multiple rows

I have a table that I'm working with that looks something like this:

Code    Name           Date
-------------------------------------------
10      General Fund   7/18/2013 1:36:15 PM     
100     Plain Fund     12/31/2099               
10300   Fund Name      8/12/2099                
10300   Fund Name      5/17/2099      
10300   Fund Name      12/31/2099

Some rows are identical except for their date - I want to select all the codes by the row with their greatest date, like so:

Code    Name           Date
-------------------------------------------
10      General Fund   7/18/2013 1:36:15 PM     
100     Plain Fund     12/31/2099                     
10300   Fund Name      12/31/2099

Here's what I have so far but it doesn't give me the desired result:

SELECT DISTINCT 
    t1.code, 
    t1.name, 
    t1.date, 
FROM table.fund t1
    INNER JOIN table.fund t2
    ON t1.code = t2.code
        AND TRUNC(t1.date) > TRUNC(t2.date);

Upvotes: 0

Views: 79

Answers (2)

Andrew
Andrew

Reputation: 8703

You can use windowed functions to accomplish this:

select
*
from
(
  select
  ROW_NUMBER() OVER (PARTITION BY "TheName" ORDER BY "TheDate" desc) as RN,
  fund.*
  from 
  fund
) t
where t.RN = 1

SQLFiddle

Upvotes: 0

LL1138
LL1138

Reputation: 126

select code, name, max(date) from your_table group by code, name;

Upvotes: 3

Related Questions