SELECT DISTINCT查询字符串列表

时间:2014-01-02 15:42:48

标签: asp.net sql sql-server

如何将SELECT DISTINCT Query中的单个列转换为包含逗号分隔的查询结果列表的字符串。

我的SQL查询示例:

SELECT DISTINCT FirstName FROM CompanyA WHERE DIV_Num in ('SUB.EAST', 'SUB2', 'SUB3', 'HR.SUB', 'HR.SUB2')

输出示例:

Bob
Alice
Jim

我希望得到单个字符串:

Bob, Alice, Jim

1 个答案:

答案 0 :(得分:1)

示例

Select distinct ST2.SubjectID, 
           substring((Select ','+ST1.StudentName  AS [text()]
            From dbo.Students ST1
            Where ST1.SubjectID = ST2.SubjectID
            ORDER BY ST1.SubjectID
            For XML PATH ('')),2, 1000) [Students]
     From dbo.Students ST2