获取单个记录中的所有行值

时间:2017-05-16 16:10:04

标签: sql sql-server

我有一个表格,我希望将列值以逗号enter image description here

分隔的单个记录

3 个答案:

答案 0 :(得分:4)

使用stuff() with select ... for xml path ('') method of string concatenation

select col1, col2, col3 = stuff(
  (
  select ','+i.col3
    from t as i
    where i.col1 = t.col1
  for xml path (''), type).value('.','nvarchar(max)')
  ,1,1,'')
from t
group by col1, col2

rextester演示:http://rextester.com/QXH88855

返回:

+------+------+-------------+
| col1 | col2 |    col3     |
+------+------+-------------+
|    1 | roy  | a,f,g,h     |
|    2 | sam  | h,k,l       |
|    3 | joe  | q,w,e,r,t,y |
+------+------+-------------+

答案 1 :(得分:2)

如果是SQL Server 2017或Vnext或SQL Azure,则可以使用string_agg

SELECT col1, col2, STRING_AGG(col3, ',') from yourtable
   GROUP BY col1, col2

答案 2 :(得分:0)

格式化输出确实应该在接收数据的程序中完成。您可以通过选择工具栏上的“输出到文件”并配置逗号分隔的输出,从SQL Server Management Studio导出到csv。

如果您确实需要将列组合成逗号分隔的单个值:

SELECT CAST(col1 AS NVARCHAR(100)) + N',' + CAST(col2 AS NVARCHAR(100)) + N',' + CAST(col3 AS NVARCHAR(100)) FROM table

相关问题