如何在sql server中基于id将多行连接成一行

时间:2017-03-03 04:19:42

标签: sql-server sql-server-2012

实际上我有三列。 ID MedID 名称。根据我的查询,我得到的结果如下所示。

ID       MedID         Name
 1       101           TestData1
 1       124           TestData2

查询

 select 
    cmd.ID, mm.MedID,mm.Name as Name
 from 
     tbl1 mm
 inner join 
      tbl2 cmd on cmd.medID= mm.MedID
  where
       cmd.ID= 1

实际上我期待的结果如下所示

 ID          MedID        Name
  1          101,124      TestData1,TestData2

那么,如何获得这样的结果,我需要在查询中做哪些更改?

任何帮助表示赞赏。在此先感谢!!!

2 个答案:

答案 0 :(得分:1)

像这样使用STUFFFOR XML PATH

select id,
    stuff((
            select ',' + cast(MedId as varchar(30))
            from t t1
            where t1.id = t.id
            order by MedID
            for xml path('')
            ), 1, 1, '') MedID,
    stuff((
            select ',' + Name
            from t t1
            where t1.id = t.id
            order by MedID
            for xml path('')
            ), 1, 1, '') Name
from t
group by id;

Demo

答案 1 :(得分:0)

DECLARE @TABLE TABLE (ID int, MedID  varchar(10), Name varchar(10))
INSERT INTO @TABLE VALUES
 (1,       '101' ,          'TestData1'),
 (1,       '124' ,          'TestData2')

SELECT t.ID
      , STUFF(( SELECT ', ' + MedID
                FROM @TABLE 
                WHERE ID = t.ID
                FOR XML PATH(''),TYPE)
                .value('.','NVARCHAR(MAX)'),1,2,'') AS MedID
      , STUFF(( SELECT ', ' + Name
                FROM @TABLE 
                WHERE ID = t.ID
                FOR XML PATH(''),TYPE)
                .value('.','NVARCHAR(MAX)'),1,2,'') AS Name           
FROM @TABLE t
GROUP BY t.ID