这是具有相同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
答案 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