I have the below data
UniqueID ID data
1 1 a
2 1 2
3 1 b
4 1 1
5 2 d
6 2 3
7 2 r
The expected output being
ID ConcatData
1 a,-,-,b,-
2 d,-,-,-,r
What we have to do is that, the number of numeric charecters has to be replaced with those many dashes(‘-‘) and then we need to merge the data for the respective id’s.
I am using the below query so far
declare @t table(UniqueID int identity(1,1), ID int, data varchar(10))
insert into @t select 1, 'a' union all select 1, '2' union all select 1, 'b'
union all select 1, '1' union all select 2, 'd' union all select 2, '3'
union all select 2, 'r'
select * from @t
;with cte1 as
(
select
UniqueId
, id
, data
, case when isnumeric(data) = 1 then cast(data as int) end Level
from @t
union all
select
UniqueId
, id
, CAST('-' as varchar(10))
, Level - 1
from cte1
where Level > 0 )
,cte2 as
(
select id, GroupID = Dense_Rank() Over(Order by id),data, DataOrder = ROW_NUMBER() over(order by UniqueID, Level)
from cte1
where Level is null or data = '-'
)
SELECT
ID
, (select data + ','
from cte2 t2
where t2.GroupID = t1.GroupID
for XML path('')
) as ConcatData
from cte2 t1
group by t1.ID ,t1.GroupID
But the output is
ID ConcatData
1 a,b,-,-,-,
2 d,r,-,-,-,
That is I am not able to position the dashes(‘-‘) in between the characters.
Please help
Try this:
Works for the sample data bove and might be a bit quicker than using cursors