如果可能,我正在寻找单个更新声明。
考虑:
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
如果他们的“领导者”是VIP = 1,我需要为rsvp组中的访客更新isVIP
所以在这种情况下,上面的2和3行将从0更新为1.第4行,第5行将保持不变
答案 0 :(得分: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'
更新语句执行后的OUTPUT
╔═══════════╦══════════╦═══════╦═══════════╦══════════╦════════╗
║ 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 ║
╚═══════════╩══════════╩═══════╩═══════════╩══════════╩════════╝
答案 1 :(得分: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;