Given that the data don't include cycles, this is an elementary exercise of traversing a tree (or trees). It is a pity that we cannot pass (hash) object references to user-written functions. If it were possible, then I would have written the recursive part as a user-written function. Here, I use the link blocks instead. The link blocks allow recursive "calls" up to 10 or 11 deep by default. But this limit can be relaxed by using the stack= option to the data statement. (This option is now documented in 9.2.) You need to create and manage call stacks by yourself, though. /* test data */ data one; input boss $ sub $; cards; Jim Kate Lisa Jim Dave Lisa Dave Erik Anna Mary Anna Ben Erik Anna . Dave Mary Tom <-- new data Mary Bill <-- new data ; run; /* find all the subs */ %let maxDepth = 100; data _null_ / stack=&maxDepth; /* main */ link setup; do until (end); set one end=end; thisBoss = boss; link find; end; link out; return; /* helpers */ setup: /* hashes */ dcl hash in(dataset:"work.one", multidata:'y'); in.definekey('boss'); in.definedata('boss','sub'); in.definedone(); dcl hash out(ordered:'yes'); out.definekey('boss','sub'); out.definedata('boss','sub'); out.definedone(); /* const and global vars */ retain OK 0; length thisBoss $8; /* call stack */ array stack_boss[&maxDepth] $8 _temporary_; array stack_sub[&maxDepth] $8 _temporary_; array stack_rc[&maxDepth] _temporary_; array stack_i[&maxDepth] _temporary_; array stack_j[&maxDepth] _temporary_; stack_top = 0; return; add: out.add(key:thisboss, key:sub, data:thisboss, data:sub); return; find: link push; if missing(thisboss) | missing(sub) then goto outoffind; /* no point adding */ if out.check(key:thisBoss, key:sub)=OK then goto outoffind; /* already there*/ link add; /* follow */ boss = sub; sub = ''; /* find_next() gets reset as soon as another find() is called. thus we have to call find() and the number of find_next() for each sibling here. 😞 */ do i = 0 by 1 until(rc^=OK); rc = in.find(); do j = 1 to i; rc = in.find_next(); end; if rc = OK then link find; end; outoffind: link pop; return; pop: boss = stack_boss[top]; sub = stack_sub[top]; rc = stack_rc[top]; i = stack_i[top]; j = stack_j[top]; top + (-1); return; push: top + 1; if top > &maxDepth then do; put "ERROR: stack overflow"; stop; end; stack_boss[top] = boss; stack_sub[top] = sub; stack_rc[top] = rc; stack_i[top] = i; stack_j[top] = j; return; out: rc = out.output(dataset:"work.two"); return; run; /* check */ proc print data=two; run; /* on lst Obs boss sub 1 Anna Ben 2 Anna Bill 3 Anna Mary 4 Anna Tom 5 Dave Anna 6 Dave Ben 7 Dave Bill 8 Dave Erik 9 Dave Jim 10 Dave Kate 11 Dave Lisa 12 Dave Mary 13 Dave Tom 14 Erik Anna 15 Erik Ben 16 Erik Bill 17 Erik Mary 18 Erik Tom 19 Jim Kate 20 Lisa Jim 21 Lisa Kate 22 Mary Bill 23 Mary Tom */
... View more