We have a sql database at work with a table, employees that has a column, report_to, which contains the username of the person that that employee reports to. What we want to do is change this representation to a numerical representation. For instance:
‘a’ reports to ‘b’ reports to ‘c’. So the representation would be something like ‘a’ = 49, ‘b’ = 50, ‘c’ = 51. if ‘d’ becomes ‘c”s boss, then ‘d’ = 52. If ‘a’ becomes the supervisor of interns ‘e’ and ‘f’, then ‘e’ and ‘f’ both are equal to 48.
As shown, starting the numbers at a non zero number allows for expansion not only upwards but also down the hierarchical chain.
The main question is, how do I convert from the current structure (“report_to”), to a numerical representation?
NOTE: this is in MSSQL
You can add a new column (rank) that should be 0.
Then the first step is to find the BIG BOSS – this should be the user who doesn’t have a boss – report_to is null. His rank will be 1.
The second step is to find his first directs. They will rank as 2. Something like:
The third step is to find directs’s directs. Something like:
The next steps are identical with step 2 and 3, until no RANK = 0 is found.
All these steps can be done in a procedure, within a WHILE statement.
In the end, if you would like to start the ranking from 50 instead on 1, then you can make an update:
or to be sure you don’t miss anything: