如何在SQL Server中将多行连接成一个字段

时间:2014-12-22 13:05:01

标签: sql sql-server database

使用简单查询,我可以执行类似

的操作
SELECT hobbies FROM peoples_hobbies WHERE person_id = 5;

并获得:

shopping

fishing  

coding

但我只想要1行,1列:

shopping, fishing, coding

表示参考 - Can I concatenate multiple MySQL rows into one field?

我想在sql server中执行此操作??

1 个答案:

答案 0 :(得分:2)

SQL Server对聚合字符串连接没有很好的支持。但你可以这样做:

select stuff((select ', ' + hobbies
              from peoples_hobbies
              where person_id = 5
              for xml path ('')
             ), 1, 2, '') as hobbies;