[英]Find matching values from one column to another column in same table SQL Server
If I have this table:如果我有这张表:
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
.我想通过每一行使用 T-SQL 到 go 并找到与每一行的
SupervisorID
对应的EmpID
,并将主管的LastName
分配给SupervisorLastName
。
So the result should be:所以结果应该是:
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.我从这个开始,但我认为它只是在单个行级别检查
SupervisorID
是否等于EmpID
,因此它不返回任何内容。
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
.我想我的第一个示例具有误导性,因为我实际上想创建列
SupervisorLastName
。 My example shows that it already exists.我的例子表明它已经存在。 Thanks
谢谢
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.我会做类似上面的事情,只需添加默认为 null 的列。然后进行交叉应用以获取正确的姓氏并更新该列。 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.话虽这么说,你已经从技术上知道主管是谁,因为那里有 ID。 So you do not need to unnecessarily repeat data in your data base.
因此,您不需要在数据库中不必要地重复数据。
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
SELECT t1.EmpID,
t1.FirstName,
t1.LastName,
t1.SupervisorID,
t2.LastName AS SupervisorLastname
FROM #testTable t1
LEFT JOIN #testTable t2 ON t2.EmpID = t1.SupervisorID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.