根据同一个表中列中的相同值更新表

时间:2015-10-26 01:46:56

标签: sql-server

我有一张这样的表

InsuredID   | EmployeeNumber    | MemberTypeID  | LinkedMemberID
----------------------------------------------------------------
1001012     | 39018             | 102           | 0
1001061     | 39018             | 100           | 0
1001147     | 39019             | 102           | 0
1001196     | 39019             | 100           | 0

我需要将此表中的LinkedMemberID更新为具有相同InsuredIDEmployeeNumber的{​​{1}}的值,以用于所有不是100的成员类型。

MemberTypeID = 100的{​​p> LinkedMemberID将保持为0。

更新后,表格看起来应该是

MemberTypeID = 100

我尝试了各种SQLupdate语句,但无法弄清楚如何执行此操作。我正在使用SQL Server 2008.请帮助。

3 个答案:

答案 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

SQL Fiddle

将其转换为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

SQL Fiddle

答案 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