Question : SQL GROUP BY Results

I am JOINing two tables, A & B on field Key1.  There is a one-to-many relationship between Table A and Table B.  Table B also contains field Key2 and StartTime.  I wish the result set to include the A.Key1 and B.Key2, but only for the earliest StartTime.

I have a less than elegent workaround...

View_1:

SELECT A.Key1, MIN(B.StartTime) AS StartTime
FROM A LEFT JOIN B ON A.Key1=B.Key1
GROUP BY A.Key1

View_2:

SELECT View_1.Key1 AS Key1, B.Key2 AS Key2
FROM View_1 LEFT JOIN B ON View_1.Key1=B.Key1 AND View_1.StartTime=B.StartTime

Basically, I want the earliest values (based on StartTime) of Key1 and Key2 for each Key1.

Is there a better way to accomplish this?

Thanks In Advance,

- Michael

Answer : SQL GROUP BY Results

here is the query involving a join and two tables (if you want min, remove desc, if you want max, put desc after order by)

select * from (
select A.key1, B.key2, rank() over (partition by key1 order by key2) rn, B.starttime
from table1 A, table2 B
where A.key1=B.key1
) x where rn=1

above gives you min key2 for each key1
Random Solutions  
 
programming4us programming4us