Here are my tables:declare @st table (id int, id2 int, dte datetime)insert into @stselect 1, 102, '03/03/2006' union allselect 2, 109, '10/03/2006' union allselect 3, 122, '05/01/2005' union allselect 4, 134, '02/23/2005'declare @dy table (id2 int, de_id int, dte2 datetime)insert into @dyselect 102, 33, '04/10/2007' union allselect 102, 34, '03/01/2006' union allselect 102, 34, '03/01/2006' union allselect 102, 35, '02/10/2002' union allselect 102, 36, '11/28/1998' union allselect 109, 39, '01/12/2007' union allselect 109, 40, '02/03/2007' union allselect 122, 30, '05/18/1998' union allselect 122, 32, '02/03/1994' union allselect 122, 33, '11/27/1992' union allselect 134, 15, '01/08/2005' union allselect 134, 16, '09/05/2005'
I need to select id from @st, plus de_id from @dy, where @st.id2=@dy.id2 and @dy.dte2 = max(dte2) for this particular id, while being lower than @st.dte.There might be multiple records in @dy with the same id2, de_id and dte2, I only need one in the results.In other words I'm expecting:id de_id dte2-----------------------1 34 '03/01/2006' <- this is the highest dte2 for 109, lower than dte for it2 NULL NULL <- no record in @dy with dte2 lower than dte3 30 '05/18/1998'4 15 '01/08/2005'
How do I write this query?Edit: I had incorrect de_id for id=3