Consider these data:
ID Year Code1 Code2
-------- -------- -------- --------
ABC123 99/00 10010 A1121
ABC123 00/01 10010 A1131
ABC123 01/02 10010 A1141
XYZ567 06/07 12501 B2213
XYZ567 07/08 12501 B2223
These four fields make up the primary key and I need to find the earliest occurrence of each instance of ID, with the three other keys. So, in this case, I would want:
ID Year Code1 Code2
-------- -------- -------- --------
ABC123 99/00 10010 A1121
XYZ567 06/07 12501 B2213
In Oracle, my current solution is to aggregate over the fourth character of Code2, which is the year index, and return the minimum then recompose the key (i.e., the varying Year part); however, this is obviously ambiguous and may not map one-to-one. (Also, this method is slow!) An ordering won’t work either because, in general, there will be multiple values under ID and Year doesn’t include the century.
I was thinking that maybe I could do a subquery for each ID and then do an ordering and pick the first item (i.e. ROWNUM=1). However, this requires at least two levels of subquery and, thus, is both awkward and slow… So, any better ideas?! Thanks 🙂
This is what analytic functions were invented for! You want something like:
I left the
order byas ??? because I don’t fully understand what you want here. It could be:or
or whatever.