SQL Select stuff

2019-07-20 11:58发布

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

2条回答
时光不老,我们不散
2楼-- · 2019-07-20 12:48

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
查看更多
啃猪蹄的小仙女
3楼-- · 2019-07-20 12:53

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
查看更多
登录 后发表回答