0

如果可能的话,我正在寻找一个更新声明。

考虑:

rsvpgroup   |   personid | isVip | firstname | lastname |   type
------------------------------------------------------------------
1                100         1       bob         smith     leader
1                101         0       john        doe       guest
1                102         0       sara        jones     guest
2                200         0       tom         ohara     leader
2                201         0       jane        doe       guest

isVIP如果他们的“领导”isVip=1,我需要为 rsvp 组中的客人更新

所以在这种情况下,上面的第 2 行和第 3 行将从 0 更新为 1。第 4、5 行将保持不变

4

2 回答 2

1
UPDATE  a
SET     a.isVip = 1
FROM    TableName a
        INNER JOIN TableName b
            ON  a.rsvpgroup = b.rsvpgroup AND
                b.[type] = 'leader' AND
                b.isVip = 1
WHERE   a.[type] = 'guest'

更新语句执行后的输出

╔═══════════╦══════════╦═══════╦═══════════╦══════════╦════════╗
║ RSVPGROUP ║ PERSONID ║ ISVIP ║ FIRSTNAME ║ LASTNAME ║  TYPE  ║
╠═══════════╬══════════╬═══════╬═══════════╬══════════╬════════╣
║         1 ║      100 ║     1 ║ bob       ║ smith    ║ leader ║
║         1 ║      101 ║     1 ║ john      ║ doe      ║ guest  ║
║         1 ║      102 ║     1 ║ sara      ║ jones    ║ guest  ║
║         2 ║      200 ║     0 ║ tom       ║ ohara    ║ leader ║
║         2 ║      201 ║     0 ║ jane      ║ doe      ║ guest  ║
╚═══════════╩══════════╩═══════╩═══════════╩══════════╩════════╝
于 2013-05-11T15:49:41.077 回答
0

这是一种使用窗口函数和 CTE 的方法:

with toupdate as (
      select t.*,
             max(case when [type] = 'leader' then IsVIP end) over
                      (partition by RSVPgroup) as LeaderIsVIP
      from t
     )
update toupdate
    set IsVIP = LeaderIsVIP
    where IsVIP <> LeaderIsVIP;
于 2013-05-11T16:06:24.183 回答