This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Getting Max Year

 
Skanda Raman
Ranch Hand
Posts: 205
Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Sheriff
Posts: 21319
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic