【问题标题】:Update one row based on value in another row根据另一行中的值更新一行
【发布时间】:2020-05-05 19:13:42
【问题描述】:

我有一个包含以下列和值的表格:

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

如果有 2 个条目具有相同的 subscriptionName 并且另一条记录在 Status 中具有值 Enabled,我如何将暂停记录的 Ignore 列更新为 True

【问题讨论】:

  • 请用您正在使用的数据库标记您的问题:mysql、oracle、sql-server...? update 语句的语法是完全特定于数据库的。
  • 是否只需要 2 个条目?还是所有大于 1 的条目?
  • 它总是必须是被暂停的条目吗?你不能:更新表 xxxx set Ignore = 'True' where SubscriptionName = 'Project Plan 3 for Faculty' and Status = 'Suspended'?

标签: sql sql-server tsql sql-update


【解决方案1】:

在 SQL Server 中,您可以使用窗口函数和可更新的 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

条件窗口max() 检查是否存在具有相同SubscriptionName 和状态'Enabled' 的另一行。

或者你可以使用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'
    )

【讨论】:

    猜你喜欢
    • 2019-09-30
    • 2020-04-17
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多