Author |
Topic |
ch9862
Yak Posting Veteran
76 Posts |
Posted - 2007-02-06 : 10:41:24
|
Here's the data:declare @act table (id int, cat varchar(2), dt datetime)insert @actselect 1, 'A', '11/02/2006' union allselect 2, 'B', '12/03/2005' union allselect 2, 'C', '12/02/2005' union allselect 2, 'D', '12/04/2005' union allselect 3, 'E', '10/09/2006'declare @inst table (id int, other_id varchar(4), type varchar(2))insert @instselect 1, '4802', 'M' union allselect 2, '4803', 'M' union allselect 2, '4803', 'B' union allselect 2, '4803', 'F' union allselect 3, '4804', 'M' I need to retrieve records from table act.For each ID I only need most recent record.Instead of ID, I need to show other_id from table inst.I have a list of other_id I need to show records for (e.g. WHERE other_id IN ('4802', '4803')).For the data above I'd expect:other_id cat dt'4802' 'A' '11/02/2006''4803' 'D' '12/04/2005' How do I write such query? |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-02-06 : 10:52:17
|
[code]SELECT distinct i.other_id, a.cat, a.dt FROM @inst AS iINNER JOIN @act AS a ON a.id = i.idWHERE a.dt = (select max(x.dt) from @act as x where x.id = a.id)[/code]Peter LarssonHelsingborg, Sweden |
 |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2007-02-06 : 10:52:36
|
[code]declare @act table (id int, cat varchar(2), dt datetime)insert @actselect 1, 'A', '11/02/2006' union allselect 2, 'B', '12/03/2005' union allselect 2, 'C', '12/02/2005' union allselect 2, 'D', '12/04/2005' union allselect 3, 'E', '10/09/2006'declare @inst table (id int, other_id varchar(4), type varchar(2))insert @instselect 1, '4802', 'M' union allselect 2, '4803', 'M' union allselect 2, '4803', 'B' union allselect 2, '4803', 'F' union allselect 3, '4804', 'M'select distinct i.other_id, a.cat, a.dtfrom @act a inner join @inst i on a.id = i.idwhere a.dt in (select max(x.dt) from @act x inner join @inst y on x.id = y.id where y.other_id = i.other_id and y.other_id in ('4802', '4803') )and i.other_id in ('4802', '4803')order by i.other_id[/code] KH |
 |
|
ch9862
Yak Posting Veteran
76 Posts |
Posted - 2007-02-06 : 20:06:24
|
Thanks so much to both of you.It depresses me though to see you come up with an answer in 5 minutes - I only asked after trying to write it for half an hour...Anyway - thanks! |
 |
|
|
|
|