【发布时间】:2020-10-20 16:07:09
【问题描述】:
【问题讨论】:
标签: sql sql-server null
【问题讨论】:
标签: sql sql-server null
一种方法使用cross apply:
select t.date, coalesce(t.value, t2.value), coalesce(t.value2, t2.value2)
from t cross apply
(select top (1) t2.*
from t t2
where t2.value is not null and t2.date < t.date
order by t2.date desc
) t2;
如果未填充的值仅针对最近的行,那么效率更高:
select t.date, coalesce(t.value, t2.value), coalesce(t.value2, t2.value2)
from t cross join
(select top (1) t2.*
from t t2
where t2.value is not null
order by t2.date desc
) t2;
如果您想更新值,那么相关子查询可能是最简单的:
更新 设置值 = (选择顶部 (1) t2.value 从 t t2 其中 t2.value 不为空并且 t2.date
【讨论】:
使用子查询:
SELECT Date
,ISNULL(Value, (SELECT TOP 1 Value From Temp T1 WHERE T.Date > T1.DATE AND T1.Value is not null)) AS Value
,ISNULL(Value2, (SELECT TOP 1 Value2 From Temp T1 WHERE T.Date > T1.DATE AND T1.Value2 is not null)) AS Value2
FROM Temp AS T
ORDER BY DATE DESC
【讨论】: