Maybe the following query might help you. To get the results used OUTER APPLY. Screenshot # 1 shows sample data and sample query output. This query can be written better, but this is something that I could come up with right now.
Hope this helps.
SELECT ITM.Id
, COALESCE(DAT.New_D, ITM.D) AS D
, ITM.DateValue
FROM dbo.Items ITM
OUTER APPLY (
SELECT
TOP 1 D AS New_D
FROM dbo.Items DAT
WHERE DAT.DateValue < ITM.DateValue
AND DAT.D <> 0
AND ITM.D = 0
ORDER BY DAT.DateValue DESC
) DAT
Screenshot # 1:

user756519
source
share