我正在使用MS SQL Server。
我有一张像这样的学生表:
StudentID,Teacher
123,Adams
124,Adams
125,Johnson
126,Johnson
127,Adams
128,Marks
我需要输出如下:
Teacher,Students
Adams,123|124|127
Johnson,125|126
Marks,128
感谢您的帮助。谢谢。
答案 0 :(得分:2)
declare @table_var table(
student_id INT,
teacher varchar(50)
)
insert into @table_var
select 123, 'Adams' union all
select 124, 'Adams' union all
select 125, 'Johnson' union all
select 126, 'Johnson' union all
select 127, 'Adams' union all
select 128, 'Marks'
select * from @table_var
select
teacher,
students = stuff((select '|' + convert(varchar, t2.student_id)
from @table_var t2
where t1.teacher = t2.teacher
for xml path(''))
,1,1,'')
from @table_var t1
group by t1.teacher