Вопрос

I have below table and want to convert into a table as shown below it. Whenever there is a missing value in a column 'name' then the value is populated from the adjacent top row. I solved my purpose by creating a self join. But in some cases 2 or 3 rows in succession are blank and i had to run my self join multiple times. Moreover I was not sure how many continuous blanks are in the data and I had to keep running self join again and again till it stopped updating any records

i am using SQL server management studio...

id  name
1   nj
2   ab
3   
4   
5   cd
6   
7   ef
8   
9   
10  gh
11  ij
12  jk

The output that I want:

id  name
1   nj
2   ab
3   ab
4   ab
5   cd
6   cd
7   ef
8   ef
9   ef
10  gh
11  ij
12  jk
Это было полезно?

Решение

As a select query, you can use a correlated subquery for this:

select id,
       (select top 1 name
        from yourtable t2
        where t2.id <= t.id and
              t2.name is not null
        order by t2.id desc
       ) as name
from yourtable t;
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top