读书人

请问一个sql语句或视图需要高手支持

发布时间: 2011-12-28 22:45:21 作者: rapoo

请教一个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

读书人网 >SQL Server

热点推荐