Home > Back-end >  Fill empty rows until find next value
Fill empty rows until find next value

Time:06-01

It's possible to have and update (T-SQL) to fill the empty rows with the previous value, until find a row with value

id Date
1 May 24, 2022
2 NULL
3 NULL
4 NULL
5 NULL
6 NULL
7 NULL
8 May 23, 2022
9 NULL
10 NULL

That's the column, I would like to write the "May 24, 2022", until the value "May 23,2022" and then "May 23,2022" until the next not NULL column

Thanks in advance.

CodePudding user response:

One possibility is to use a correlated subquery in an update:

update t 
  set date = (select min(date) from t t2 where t2.id < t.id)
where date is null

Demo Fiddle

CodePudding user response:

We would like to use last_value but ignore nulls doesn't work in SQL Server.
We can use a CTE and inline sub-query.

create table t(id int, date_ varchar(10));
insert into t values (1,'2022-05-24'),(8,'2022-05-23');
insert into t (id) values(2),(3),(4),(5),(6),(7),(9),(10);

10 rows affected

with cte as(
select 
  id, 
  date_,
  (select max(id) from t t2 where t2.id <= t.id and date_ is not null ) idd
from t)
select
  id,
  (select date_ from cte c where c.id = d.idd) "date"
from cte d
order by id
id | date      
-: | :---------
 1 | 2022-05-24
 2 | 2022-05-24
 3 | 2022-05-24
 4 | 2022-05-24
 5 | 2022-05-24
 6 | 2022-05-24
 7 | 2022-05-24
 8 | 2022-05-23
 9 | 2022-05-23
10 | 2022-05-23

db<>fiddle here

  • Related