aspose file tools*
The moose likes JDBC and the fly likes Getting Max Year Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Getting Max Year" Watch "Getting Max Year" New topic
Author

Getting Max Year

Eshwar Prasad
Ranch Hand

Joined: Mar 21, 2008
Posts: 202

I am doing a application where i have to join table A and Table B with ID field and based on Max year in Table B i need to display the Place of the user. I tried using below query, I am not getting as expected. Please advise me here.

TABLEA
-------

------------
ID | NAME | PLACE
1 | JOHN | AMERICA
2 | JOHN | LONDON

TABLE B
-------

ID | YEAR
1 | 2009
2 | 2011

SELECT MAX(A.ID), PLACE,NAME FROM A,B
WHERE
A.ID=B.ID GROUP BY PLACE,NAME;
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18570
    
    8

From what you posted I can tell what the output of that query would be. But I can't tell what you expected it would be, because you didn't mention that. So asking us why the actual output is different from what you expected isn't really fair. Don't you agree?
m coffee
Greenhorn

Joined: Nov 10, 2010
Posts: 5
One way that would work is like this:

select a.personname, a.place, c.maxpersonyear
from tablea a,
(select a.personname, max(b.personyear) as maxpersonyear , max(b.id) as maxid
from tablea a, tableb b
where a.id = b.id
group by a.personname) c
where a.personname = c.personname and a.id = c.maxid
group by a.personname, a.place, c.maxpersonyear

However -- using id this way seems odd to me. You're assuming that the maximum id is also the last year. You should have a real date, not just year, because presumably someone can be in 2 places in a single year. If you have a real date, then you might have to manipulate this more to get the id which goes with that real date, and join that id to your tablea.
 
 
subject: Getting Max Year