Home > Back-end >  Find matching values from one column to another column in same table SQL Server
Find matching values from one column to another column in same table SQL Server

Time:03-12

If I have this table:

enter image description here

I want to use T-SQL to go through each row and find the EmpID that corresponds to the SupervisorID for each row, and assign the LastName of the supervisor to SupervisorLastName.

So the result should be:

enter image description here

I started with this, but I think it is just checking if SupervisorID is equal to EmpID at the individual row level so it returns nothing.

CASE
    WHEN (EmpID = SupervisorID) 
        THEN CAST(LastName AS CHAR(30)) 
END AS SupervisorLastName

I guess my first example was misleading because I actually want to create the column SupervisorLastName. My example shows that it already exists. Thanks

CodePudding user response:

Could you try something like this?

SELECT t1.*, 
       t2.LastName AS SupervisorLastname 
FROM table1 t1 
LEFT JOIN (SELECT EmpID, LastName FROM table1) t2 ON t2.EmpID = t1.SupervisorID

CodePudding user response:

  ALTER TABLE TableName
  ADD SuperVisorLastName NVARCHAR(100) DEFAULT NULL;

  UPDATE TB1
  SET SuperVisorLastName = TB2.LastName
  FROM TableName TB1
  CROSS APPLY (SELECT TOP 1 * FROM TableName TB2 WHERE TB2.EmpID = 
  TB1.SupervisorID) TB2

I would do something like the above just add the column defaulted to null. Then do a cross apply to get the correct last name and update the column. Not copy and pastable but should give you a rough idea of how you could do it.

That being said you already technically know who the supervisor is because of the ID on there. So you do not need to unnecessarily repeat data in your data base.

  • Related