I have a table with below structure:
OLD_ID New_ID Month_Number
------ ------ ------------
A 1
A B 2
B C 3
C D 4
I need an output out of this table for an ID 'A' as:
New_ID Oldest_Id Latest_ID
------ --------- ---------
A A D
B A D
C A D
D A D
The oldest_Id and Latest_id can be found using month_number.
Please advice, i am new to SQL.
This answer assumes Microsoft SQL Server, but with tweaks to the syntax this could work for any DB type provided that it features temporary tables, row counts and user-defined variables (the latter simply for a safety cutoff lest you have a loop). This answer also assumes that the source table is
#ExampleTable
, the[New_ID]
column contains all the IDs, and that older/newer IDs should only be regarded if the respective[Month_Number]
values are appropriate, e.g. LTE the "newer" ID's[Month_Number]
for older IDs.Basically what I would envision is to make two temporary tables: the first to list each
[ID]
along with the first[Old_ID]
for the[ID]
, and the second the same albeit for the last[New_ID]
:The records in
#ID1
and#ID2
are setup to reference themselves to begin with. Then, for each pass in the loops, the IDs' values are updated with the next step if available. When there is nothing else to do, the iterations cease.Here is what happens in each pass:
The
@cutoff
variable is simply to prevent this from looping forever should ID 'A' reference old ID 'B' and ID 'B' reference old ID 'A', to give an example.This isn't a terribly efficient method, and you could probably do better with some practice: for example, by combining both Oldie/Newie actions in one, but I'll leave that to you. :)