Domanda

I'm quite new to sql and I need your help with this situation, which might be basic stuff for most of you:

I've got a table "Employee", which has amongst others the attributes ID and BOSS_ID. The BOSS_ID of the top level bosses is NULL.

Now I'd like to have a table, which lists the employee id together with the id of the particular top level boss.

What I've already got did is this recursive query, which returns all employees with the id of the next higher level boss:

WITH TopBosses(ID,NAME, BOSS_ID)
AS
(
    SELECT ID,NAME, BOSS_ID
    FROM EMPLOYEE
    WHERE BOSS_ID IS NULL
    UNION ALL

    SELECT EMPLOYEE.ID,EMPLOYEE.NAME, EMPLOYEE.BOSS_ID
    FROM EMPLOYEE
    INNER JOIN TopBosses
        ON EMPLOYEE.BOSS_ID = TopBosses.ID
)
SELECT ID,NAME, BOSS_ID
FROM TopBosses

But as the next level boss id is already part of the table "Employee", this is pretty useless to me :) I just don't get the final step how I could always get the particular top level boss.

Thank you for your replies!

È stato utile?

Soluzione

You can include the Top Bosses ID in each row

e.g.

WITH TopBosses(ID,NAME,BOSS_ID,TOP_ID)
AS
(
    SELECT ID,NAME,NULL AS BOSS_ID,ID AS TOP_ID
    FROM EMPLOYEE
    WHERE BOSS_ID IS NULL
    UNION ALL

    SELECT EMPLOYEE.ID,EMPLOYEE.NAME,EMPLOYEE.BOSS_ID,TopBosses.TOP_ID
    FROM EMPLOYEE
    INNER JOIN TopBosses
        ON EMPLOYEE.BOSS_ID = TopBosses.ID
)
SELECT ID,NAME,BOSS_ID,TOP_ID
FROM TopBosses
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top