ManiMuthuPandi ManiMuthuPandi - 4 months ago 14
SQL Question

How to use join here

I am having the below table

enter image description here

From this table I have to display Username and SupervisorName. I am having both

userID
, and
SuperviosrUid
in the same table.

My Expected Output is:

enter image description here

Answer

Just join the table with itself:

SELECT u.Name As UserName,
       s.Name As SupervisorName
FROM dbo.TableName u
LEFT OUTER JOIN dbo.TableName s
    ON u.SupervisorUID = s.UID

I've used a LEFT OUTER JOIN for the case that a user could have no supervisor. If it cannot be NULL you can use INNER JOIN.