将多行转换为一列SQL Server 2008

时间:2014-12-05 15:47:48

标签: sql sql-server-2008

我的查询结果如下所示。如您所见,grp_code列是相同的。

我想从find_description列中创建一个字符串,并将结果显示在一列中。我有几个这样的项目,我希望有一个简单的方法。

Group Description          Grp Code        Find Code           Find description
Pre Procedure              CENTL8          FND102757           Labs Reviewed
Pre Procedure              CENTL8          FND102758           Consent verified
Pre Procedure              CENTL8          FND102759           History
Pre Procedure              CENTL8          FND120760           Assemble equipment

需要的结果

Labs Reviewed, Consent Verified, History, Assemble equipment

1 个答案:

答案 0 :(得分:0)

您可以使用stuff函数和xml路径来构建字符串分隔列表列。

  SELECT
     Group_description
     ,Grp_code
     ,Find_code
     ,find_descriptionString = STUFF((
          SELECT ', ' + md.find_description
          FROM *table_name*
          WHERE m.group_code = md.group_code
          FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM *table_name* m
GROUP BY m.grp_code
         ,group_description
         ,find_code