Reputation: 736
I have project
table.
This is my query which is fetching following results.
select top 5 proj_ID, Proj_NM
from project
Output:
proj_ID Proj_NM
-------------------
20 test1
21 test2
22 test3
24 test4
25 test5
I want to get this output instead. Can any one pls help.
proj_ID Proj_NM All_Proj_NM
---------------------------------
20 test1 test1,test2,test3,test4,test5
21 test2 test1,test2,test3,test4,test5
22 test3 test1,test2,test3,test4,test5
24 test4 test1,test2,test3,test4,test5
25 test5 test1,test2,test3,test4,test5
Upvotes: 2
Views: 1691
Reputation: 28423
Try this
Select Distinct ST2.proj_ID,ST2.Proj_NM,
substring((Select ',' + ST1.Proj_NM AS [text()]
From project ST1
WHERE ST1.Proj_NM IN (SELECT Top 5 Proj_NM From Projects )
ORDER BY ST1.proj_ID
For XML PATH ('')),2, 1000) [Pr_Name]
From dbo.project ST2
Upvotes: 1
Reputation: 43023
You can use FOR XML PATH
for that
select top 5 proj_ID, Proj_NM,
(select STUFF( (select top 5 ',' + Proj_NM
from project
order by proj_id
FOR XML PATH('')
), 1, 1, '')) AS All_Proj_NM
from project
order by proj_ID
Upvotes: 4