逗号分隔结果多列sql server

时间:2012-09-01 06:45:52

标签: sql sql-server-2008 tsql

我有一张价值表:

Key1     Key2     ColumnKey 
============================
1        idx1      here
2        idx2      there

我需要返回,因为多个列结果用逗号分隔。示例:

1,2   idx1,idx2,      here,there

3 个答案:

答案 0 :(得分:5)

select stuff(T.X.query('Key1').value('.', 'varchar(max)'), 1, 1, '') as Key1,
       stuff(T.X.query('Key2').value('.', 'varchar(max)'), 1, 1, '') as Key2,
       stuff(T.X.query('ColumnKey').value('.', 'varchar(max)'), 1, 1, '') as ColumnKey
from 
  (
  select ','+cast(Key1 as varchar(10)) as Key1,
         ','+Key2 as Key2,
         ','+ColumnKey as ColumnKey
  from YourTable
  order by Key1
  for xml path(''), type
  ) T(X)

SE-Data

答案 1 :(得分:0)

试试这个:

;WITH CTE as(
select *,1 rn from test101)
select (STUFF((select ','+cast(Key1 as varchar(10)) from CTE  where CTE.rn=m.rn for xml path('')),1,1,'')) key1,
(STUFF((select ','+Key2  from CTE  where CTE.rn=m.rn for xml path('')),1,1,'')) key2,
(STUFF((select ','+ColumnKey from CTE  where CTE.rn=m.rn for xml path('')),1,1,'')) ColumnKey
from CTE m
group by rn

答案 2 :(得分:0)

您是否知道CodePlex具有用户定义聚合 GROUP_CONCAT 的开源CLR实现。安装就像在服务器上运行SQL脚本一样简单。

http://groupconcat.codeplex.com/

它有4个group_concat实现

  • GROUP_CONCAT - 默认分隔符是,(逗号)

  • GROUP_CONCAT_D - 您可以指定分隔符

  • GROUP_CONCAT_DS - 您可以指定分隔符,排序顺序(1作为asc顺序,2作为desc顺序)

  • GROUP_CONCAT_S - 您可以指定排序顺序