首页 > 解决方案 > 如何更新记录属于同一分区 SQL Server

问题描述

我在包含以下数据的数据库中有一个表:

     GroupId    ExceptionId ParentExceptionId   row
       1           101           NULL            1
       1           102           NULL            2
       1           103           NULL            3
       2           104           NULL            1
       2           105           NULL            2
       2           106           NULL            3
       3           107           NULL            1
       3           108           NULL            2`

我写了一个以下查询来获取上面的行号:

    with CTE_RN as
    (
     SELECT  a.[GroupId], a.[SolId], a.[id],ParentExceptionId,
     ROW_NUMBER() OVER(PARTITION BY a.[GroupId] ORDER BY a.[GroupId]) AS [row]
     FROM [dbo].[trn_Report6_Zone1_Exception] a)
     select * from cte_rn`

预期输出:使用具有相同组 ID 的第一条记录进行
更新ParentExceptionId,并保持该第一条记录为空。ExceptionIdParentExceptionId

     GroupId    ExceptionId ParentExceptionId   row
       1           101           NULL            1
       1           102           101             2
       1           103           101             3
       2           104           Null            1
       2           105           104             2
       2           106           104             3
       3           107           NULL            1
       3           108           107             2`

标签: sqlsql-serverdatabase

解决方案


您可以使用first_value函数:

select GroupId, ExceptionId, 
       (case when f_value <> ExceptionId then f_value end) as ParentExceptionId, row
from (select *, first_value(ExceptionId) over (partition by GroupId order by ExceptionId) f_value
      from [dbo].[trn_Report6_Zone1_Exception] a
     ) a;

以同样的方式,您可以使用updateablecte :

with a as (
     select *, first_value(ExceptionId) over (partition by GroupId order by ExceptionId) f_value
     from [dbo].[trn_Report6_Zone1_Exception] a
 )

update a
     set ParentExceptionId  = f_value
where f_value <> ExceptionId;

推荐阅读