SQL:如何用相同的值填充两个特定行之间的行?

SQL:如何用相同的值填充两个特定行之间的行?,sql,sql-server,tsql,sql-server-2008-r2,common-table-expression,Sql,Sql Server,Tsql,Sql Server 2008 R2,Common Table Expression,我需要将两个'AL'或两个'MX'之间的行填充/替换为'-',值为'AL'或'MX',具体取决于'-'出现的位置。在本例中,我只使用了2个“uid”(实际上我有更多的uid)。此外,表是按ASC中的uid和code_date列排序的 为了便于理解,我有以下表格: 但我想要这样的东西: 我正在使用SQLServer2008。有没有关于如何实现这一目标的建议 我使用以下代码创建了表: DECLARE @Customers TABLE (uid bigint, code_date

我需要将两个'AL'或两个'MX'之间的行填充/替换为'-',值为'AL'或'MX',具体取决于'-'出现的位置。在本例中,我只使用了2个“uid”(实际上我有更多的uid)。此外,表是按ASC中的uid和code_date列排序的

为了便于理解,我有以下表格:

但我想要这样的东西:

我正在使用SQLServer2008。有没有关于如何实现这一目标的建议

我使用以下代码创建了表:

DECLARE @Customers TABLE
    (uid bigint,
     code_date date,
     Value nchar(10)
    ) 

INSERT  INTO @Customers
VALUES  (1591, '2016-08-01', ''),
    (1591, '2016-08-02', ''),
    (1591, '2016-08-03', 'AL'),
    (1591, '2016-08-04', '-'),
    (1591, '2016-08-05', '-'),
    (1591, '2016-08-06', '-'),
    (1591, '2016-08-07', '-'),
    (1591, '2016-08-08', '-'),
    (1591, '2016-08-09', 'AL'),
    (1591, '2016-08-10', ''),
    (1591, '2016-08-11', 'AL'),
    (1591, '2016-08-12', ''),
    (1082, '2016-02-01', ''),
    (1082, '2016-02-02', ''),
    (1082, '2016-02-03', ''),
    (1082, '2016-02-04', ''),
    (1082, '2016-02-05', 'MX'),
    (1082, '2016-02-06', '-'),
    (1082, '2016-02-07', '-'),
    (1082, '2016-02-08', '-'),
    (1082, '2016-02-09', '-'),
    (1082, '2016-02-10', '-'),
    (1082, '2016-02-11', '-'),
    (1082, '2016-02-12', 'MX');

    SELECT * FROM @Customers ORDER BY uid, code_date ASC

对于
选择
查询,只需使用
外部应用

select t.*, coalesce(t.value, t2.value) as new_value
from t outer apply
     (select top 1 t2.*
      from t t2
      where t2.uid = t.uid and t2.code_date < t.code_date and t2.value is not null
      order by t2.code_date desc
     ) t2;
声明@x varchar(1000)=”
更新@Customers
设置@x=value=(当@x''和值不在('-',@x)中时为大小写,然后在''else@x end')+(当值='-'时为大小写,然后在值=@x和''else value end'中为'')
其中值为“”

@user7020195此解决方案无法解决“我的问题”。我试图用其中一个填充相同值“AL”或“MX”之间的“-”值。@user7020195非常抱歉!答案是正确的。我最初没有正确检查。谢谢
select t.*, coalesce(t.value, t2.value) as new_value
from t outer apply
     (select top 1 t2.*
      from t t2
      where t2.uid = t.uid and t2.code_date < t.code_date and t2.value is not null
      order by t2.code_date desc
     ) t2;
update t
    set value = t2.new_value
    from t outer apply
         (select top 1 t2.*
          from t t2
          where t2.uid = t.uid and t2.code_date < t.code_date and t2.value is not null
          order by t2.code_date desc
         ) t2
    where t.value is null;
declare @x varchar(1000) = ''

update @Customers
set  @x = value = (case when @x <> '' and value not in ('-',@x) then '' else @x end) + (case when value = '-' then '' when value = @x then ''  else value end)
where value <> ''