Click here to Skip to main content
15,881,757 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Result Obtained:
N0    Name
1       a
1       b
1       c
2       d


Expected Result :
N0  Name
1   abc
2   d
Posted
Updated 30-Jul-13 23:13pm
v2

1 solution

Check this..

SQL
Create Table #Temp(No int, Name Nvarchar(40))
Insert into #Temp
Select 1,'a' Union all
Select 1,'b' Union all
Select 1,'c' Union all
Select 2,'d'

Select Distinct t.No, 
STUFF((Select Distinct a.Name From #Temp a 
       Where a.No=t.No 
       for Xml Path(''),TYPE).value('.','VARCHAR(max)'), 1, 0, '') as CombinedList 
From #Temp t

Drop Table #Temp


Output:
SQL
No	CombinedList
---     ------------
1	abc
2	d


Using a Recursive Cte...
SQL
Create Table #Temp(No int, Name Nvarchar(40))

Insert into #Temp 
Select 1,'a' Union all
Select 1,'b' Union all
Select 1,'c' Union all
Select 2,'d'

;With cte (No,Name,RankNo) as
(
Select No,Name,ROW_NUMBER() Over(Partition by No Order by Name) from #Temp 
)

,recurs_cte (No,CombinedName,RankNo) AS
(
SELECT Distinct No,Cast(Name as Nvarchar(Max)),RankNo FROM cte WHERE RankNo=1
UNION ALL
SELECT c.No,Cast(r.CombinedName + c.Name as Nvarchar(Max)),c.RankNo FROM recurs_cte r
INNER JOIN cte c ON r.No=c.No 
Where c.RankNo=r.RankNo+1
)

Select No,CombinedName From recurs_cte r 
Where RankNo in (Select Max(RankNo) from recurs_cte where No=r.No) Order by No

Drop Table #Temp
 
Share this answer
 
v7
Comments
Maciej Los 31-Jul-13 5:43am    
+5!
Raja Sekhar S 31-Jul-13 5:59am    
Thank you Maciej Los...
Maciej Los 31-Jul-13 6:28am    
Another 5! - If i could... ;)
Raja Sekhar S 31-Jul-13 6:30am    
I Think that's not possible... Thanks again...
Keerthi Kumar(Andar) 1-Aug-13 2:30am    
thanks a lot Mr Raja Shekhar S.Thats a great answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900