首页 > 解决方案 > 复制相同的值,直到新值出现在 SQL Server 中

问题描述

我的表中有以下数据

Name Break 
AA    1      
BB    1      
CC           
DD           
EE    1      
FF            
GG    1      

现在我想要下面的结果。

规则就像在更​​新名称列中复制名称列的值,直到我们在中断列中找到 1。

Name Break UpdatedName
AA    1      AA
BB    1      BB
CC           BB
DD           BB
EE    1      EE 
FF           EE 
GG    1      GG 

我怎样才能得到上述结果?

标签: sql-server

解决方案


您还可以使用嵌套的 Select 查询,如下所示 see live demo

注意: 我假设名称不一定按字母顺序排列

; with cte as 
(select rn=row_number() over (order by (select NULL)), * from tbl)

select 
c1.Name, 
c1.[Break],
updateValue= 
 case 
   when c1.[break] is not null 
   then C1.Name 
   else
(
   select 
     TOP 1 
     c2.Name 
   from cte c2 
   where c2.rn<c1.rn 
   and c2.[break] is NOT NULL 
   order BY rn desc
) end
from cte c1  
    order by c1.rn

推荐阅读