我需要用'来填充/替换行。 - '在两个AL'之间或两个' MX'价值' AL'或者' MX'取决于' - '出现。出于这个例子的目的,我只使用2' uid' (我实际上有更多的uid)。此外,该表按ASC中的uid和code_date列进行排序
为了便于理解,我有这张表:
但我希望有这样的事情:
我正在使用SQL Server 2008.关于如何实现这一点的任何建议???
我使用以下代码创建了表:
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
答案 0 :(得分:4)
+ scale_y_reverse()
答案 1 :(得分:1)
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 <> ''
答案 2 :(得分:0)
对于select
查询,只需使用outer apply
:
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
中使用类似的逻辑。
作为update
,这将是:
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;