Hi @ojmp2001 ojmp2001 ,
Welcome to Microsoft Q&A!
After checking, below insert row is missing.
Insert into #temp values (2,'hmn')
What is the version of your SQL Server?
If your version is SQL Server 2012 and later, please refer below and check whether it is helpful to you.
Create table #temp
(ID INT,
Testv Varchar(max)
)
Insert into #temp values (1,'')
Insert into #temp values (1,'abc')
Insert into #temp values (1,'def')
Insert into #temp values (1,'')
Insert into #temp values (1,'ijk')
Insert into #temp values (2,'hmn')
Insert into #temp values (2,'xyz')
Insert into #temp values (2,'')
Insert into #temp values (2,'klm')
Insert into #temp values (2,'nop')
;with cte as (
select id,IIF(Testv='',NULL,Testv) Testv,ROW_NUMBER() over (partition by id order by (select 1)) rn from #temp)
,cte1 as (
select *,max(Testv) over (partition by id,c) Testvv from (
select *,c=count(Testv) over (partition by id order by rn)
from cte )a)
select ID,isnull(Testv,'')Testv,
isnull(lag(Testvv) over (partition by id order by rn),'') desired
from cte1
Output:
ID Testv desired
1
1 abc
1 def abc
1 def
1 ijk def
2 hmn
2 xyz hmn
2 xyz
2 klm xyz
2 nop klm
Best regards,
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.