SQL Select stuff

限于喜欢 提交于 2019-12-24 05:18:08

问题


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

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/22292662/sql-select-stuff

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!