Click to See Complete Forum and Search --> : Getting corresponding fields of max date


robin thomas
04-10-2007, 09:51 AM
I have 3 fields in my table. id,date and quantity. I want to take the value of quantity field corresponding to max of date field. Please help me.

russell
04-10-2007, 02:29 PM
what dbms?

something like this will work, depending on dbms

select a.id, a.date, a.qty
from yourtable a
join (
select id, max(date) dt
from yourtable
group by id
) b
on a.id = b.id
and a.date = b.date

robin thomas
04-11-2007, 02:00 AM
Sorry. I havnt given full information. Those fields are from 2 tables.date is in another table. You can join the tables using id and sid. Please help me.

russell
04-11-2007, 02:21 PM
post the schema of the 2 tables. also what is dbms?

robin thomas
04-13-2007, 12:57 AM
post the schema of the 2 tables. also what is dbms?

DB is sql 2005

Table A
id int,qty double

Table B

aid int, ddate datetime

russell
04-13-2007, 01:45 PM
select a.id, b.dt, a.qty
from TableA a
join (
select aid, max(ddate) dt
from TableB
group by aid
) b
on a.id = b.aid