按列将记录组合​​在一起

时间:2017-12-20 09:56:26

标签: sql-server

这是具有相同ID的不同技术的表

id   technology       
------------------
1    MCA           
1    BSC SCIENCE   
2    BTECH         
3    BTECH         
3    MTECH  

如何将输出组合并为:

id   technology       
--------------------------
1    MCA, BSC SCIENCE               
2    BTECH         
3    BTECH, MTECH   

2 个答案:

答案 0 :(得分:2)

使用STUFF功能& FOR XML PAT作为下一个: -

 STUFF((SELECT DISTINCT ', ' + technology
           FROM #tempTable b 
           WHERE b.id = a.id 
          FOR XML PATH('')), 1, 2, '')

<强>演示: -

create table #tempTable 
(
id int,
technology nvarchar(max)
)

insert into #tempTable values    
 (1 ,'MCA')
,(1 ,'BSC SCIENCE')
,(2 ,'BTECH')
,(3 ,'BTECH')
,(3 ,'MTECH')


SELECT id, displayname = 
    STUFF((SELECT DISTINCT ', ' + technology
           FROM #tempTable b 
           WHERE b.id = a.id 
          FOR XML PATH('')), 1, 2, '')
FROM #tempTable a
GROUP BY id

<强>结果: -

1   BSC SCIENCE, MCA
2   BTECH
3   BTECH, MTECH

答案 1 :(得分:0)

declare @tab table(id int,  technology varchar(30))
insert into @tab values(1 ,   'MCA'),
(1,    'BSC SCIENCE'),
(2 ,   'BTECH')       ,  
(3 ,   'BTECH')        ,
(3 ,   'MTECH')  


SELECT t1.ID, 
    STUFF(
                 (SELECT ',' + technology FROM @tab t where t.id = t1.id FOR XML PATH ('')), 1, 1, ''
               ) 
FROM @tab t1 GROUP BY id

输出

ID  (No column name)
1   MCA,BSC SCIENCE
2   BTECH
3   BTECH,MTECH