如何根据某些特定条件更新表?

时间:2017-05-18 19:21:07

标签: sql sql-server tsql sql-server-2012

我有一张桌子,如下所示。 enter image description here

我希望将其更新到下面。 enter image description here

基本上,根据A_ID<>0 and B_ID<>0, C_ID=0的记录,如果他们的相应记录具有相同的A_ID and B_ID,而C_ID<>0(在这种情况下为A_ID=1001 and A_ID=1002),请设置{{ 1}},IsCurrent=0到相应的ActiveTo

由于

1 个答案:

答案 0 :(得分:2)

嗯。嗯。 。 。您可以将记录标识为:

select t.*
from (select t.*,
             lead(ActiveFrom) over (partition by a_id, b_id order by c_id) as next_ActiveFrom
      from t
     ) t
where c_id = 0 and next_ActiveFrom is not null;

然后更新它们:

with toupdate as (
      select t.*
      from (select t.*,
                   lead(ActiveFrom) over (partition by a_id, b_id order by c_id) as next_ActiveFrom
            from t
           ) t
      where c_id = 0 and next_ActiveFrom is not null
     )
update toupdate
    set isactive = 0,
        activeTo = dateadd(second, -1, next_ActiveFrom);