日期:2014-05-19  浏览次数:20523 次

请教一个sql语句或视图,需要高手支持!
把下表
id   name   class
1     aaa       A
1     aaa       B
2     bbb       C
2     bbb       D
2     bbb       E

变成
id   name   class
1     aaa       A,B,C
2     bbb       C,D,E

------解决方案--------------------
要用函数:

--测试数据
create table csdn(id int,txt varchar(10))
insert csdn
select 1, 'a ' union all
select 1, 'b ' union all
select 1, 'c ' union all
select 2, 'aa ' union all
select 2, 'bb ' union all
select 2, 'cc ' union all
select 3, 'aaa ' union all
select 3, 'bbb '
--select * from csdn
go

create function Gettxt(@id int)
returns varchar(8000)
as
begin
declare @s varchar(8000)
set @s= ' '
select @s=@s + ', ' +txt from csdn where id=@id
--return @s
return stuff(@s,1,1, ' ')
end
go

select id,dbo.Gettxt(id) txt from csdn group by id
go

drop function Gettxt
drop table csdn
go