我有一张这样的表
InsuredID | EmployeeNumber | MemberTypeID | LinkedMemberID
----------------------------------------------------------------
1001012 | 39018 | 102 | 0
1001061 | 39018 | 100 | 0
1001147 | 39019 | 102 | 0
1001196 | 39019 | 100 | 0
我需要将此表中的LinkedMemberID
更新为具有相同InsuredID
和EmployeeNumber
的{{1}}的值,以用于所有不是100的成员类型。
MemberTypeID = 100
的{p> LinkedMemberID
将保持为0。
更新后,表格看起来应该是
MemberTypeID = 100
我尝试了各种SQLupdate语句,但无法弄清楚如何执行此操作。我正在使用SQL Server 2008.请帮助。
答案 0 :(得分:0)
您可以使用APPLY
功能:
SELECT
t.InsuredID,
EmployeeNumber,
MemberTypeID,
LinkedMemberID = CASE WHEN t.MemberTypeID = 100 THEN LinkedMemberID ELSE x.InsuredID END
FROM tbl t
OUTER APPLY (
SELECT InsuredID
FROM tbl
WHERE EmployeeNumber = t.EmployeeNumber
AND MemberTypeID = 100
)x
将其转换为UPDATE
语句:
UPDATE t
SET t.LinkedMemberID = x.InsuredID
FROM tbl t
OUTER APPLY (
SELECT TOP 1 InsuredID
FROM tbl
WHERE EmployeeNumber = t.EmployeeNumber
AND MemberTypeID = 100
ORDER BY InsuredID DESC
)x
WHERE t.MemberTypeID <> 100
答案 1 :(得分:0)
如果我理解正确,您需要update
声明,并且可以使用join
执行您想要的操作:
update toupdate
set LinkedMemberID = t.InsuredID
from table toupdate join
table t
on toupdate.EmployeeNumber = t.EmployeeNumber and
t.MemberTypeID = 100
where toupdate.MemberTypeID <> 100;
答案 2 :(得分:0)
你可以试试这个:
UPDATE Your_Table
SET LinkedMemberID = (SELECT TOP 1 T.InsuredID
FROM Your_Table T
WHERE T.EmployeeNumber = Your_Table.EmployeeNumber
AND T.MemberTypeID = 100)
WHERE MemberTypeID <> 100