Please see the following SQL code.
Declare @LookUp table (id int,val varchar(12))
insert into @LookUp values (1,'A'),(1,'D'),(1,'X'),(2,'B'),(2,'F')
Declare @summary table (id int,val varchar(2000))
------------------------------
Declare @value varchar(30)
Declare @start int = 1, @end int = (Select count(Distinct id) from @LookUp)
While @start <= @end
Begin
Set @value = ''
Select @value = @value + '|' + val From @LookUp Where id = @start
Insert into @summary
Select @start,Right(@value,Len(@value)-1)
Set @start = @start + 1
End
Select * From @summary
With the following query, I am grouping based on Id, and making the values with in a group, as comma-separated values.
Input:
Output:
I have done this using a loop, which is not performing very well when it comes to large amount of data.
Can we do this avoiding a loop?
Note: Assume that @lookup.id is continuous.