简体   繁体   中英

Update one row based on value in another row

I have an table with following columns and values:

SubscriptionName, Status, Ignore
Project Plan 3 for faculty, Enabled, Null
Project Plan 3 for faculty, Suspended, Null

How can I update the Ignore column to True for the suspended record, if there are 2 entries with the same subscriptionName and the other record has the value Enabled in Status

In SQL Server, you can do this with window functions and an updatable CTE:

with cte (
    select 
        t.*,
        max(case when status = 'Enabled' then 1 end) 
            over(partition by SubscriptionName) has_enabled
    from mytable t
)
update cte 
set ignore = 'True'
where status = 'Suspended' and has_enabled = 1

The conditional window max() checks if another row exists with the same SubscriptionName and status 'Enabled' .

Or you can use exists :

update t 
set ignore = 'True'
from mytable t
where 
    status = 'Suspended' 
    and exists (
        select 1 
        from mytable t1 
        where t1.SubscriptionName = t.SubscriptionName and t1.status = 'Enabled'
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM