tags:

views:

77

answers:

4

If I have records:

Row  Date,        LocationID, Account
1    Jan 1, 2008  1           1000
2    Jan 2, 2008  1           1000
3    Jan 3, 2008  2           1001
4    Jan 3, 2008  1           1001
5    Jan 3, 2008  3           1001
6    Jan 4, 2008  3           1002

I need to get the row (date, locatinid, account) where the row has the most recent date for each distinct locationid:

4    Jan 3, 2008  1           1001
3    Jan 3, 2008  2           1001
6    Jan 4, 2008  3           1002
A: 

Try something like:

select *
from mytable t1
where date = (select max(date) from mytable t2
              where t2.location = t1.location);
Tony Andrews
It has the small problem that if you have two entries with the exact same date, you might get two results.
Paul Tomblin
A: 
select t.* from mytable t,
(select max(Date) as Date,LocationID from mytable group by LocationID) t1 
where t.Date = t1.Date and t.LocationID = t1.LocationID 
order by t1.LocationID
Dmitry Khalatov
I had the same solution, I just used a different syntax to perform the join.
Jim
A: 
SELECT t1.*
FROM mytable t1
  LEFT OUTER JOIN mytable t2
  ON (t1.locationid = t2.locationid 
    AND (t1.date < t2.date OR t1.date = t2.date AND t1.row < t2.row))
WHERE t2.row IS NULL;

This solution returns only one row per locationid, even if there are multiple rows with the same max date.

Bill Karwin
+2  A: 

I think this would work:

SELECT t1.*
FROM table t1
  JOIN (SELECT MAX(Date), LocationID
        FROM table
        GROUP BY Date, LocationID) t2 on t1.Date = t2.Date and t1.LocationID = t2.LocationID
Jim
Thanks, worked like a charm. I actually added a common table expression for table because the where clause was quite involved in my scenario, and I wanted to avoid writing it out twice in the outer select and the inner select.
Jeremy