日期:2014-05-17  浏览次数:20507 次

表中两个字段相同,如何删除重复的字段,保留不重复的字段并以逗号分隔?
表中两个字段相同,如何删除重复的字段,保留不重复的字段并以逗号分隔?

一张表里面以id,name字段为唯一字段,当几条记录的这两个字段完全相同时,需要删除重复字段,保留不重复的字段并以逗号分隔,如下表
id name type
1  北京  综合
1  北京  专业
2  天津  专业
2  天津  综合
以id、name为唯一字段,第一条和第二条,第三条和第四条的id、name完全相同,
需要得到如下结果:
id name type
1  北京  综合,专业
2  天津  专业,综合

请问各位老师这种sql语句怎样写?
删除重复? 逗号分隔

------解决方案--------------------
declare @tab table
(
id int,
name nvarchar(50),
type nvarchar(50)
)

insert into @tab(id,name,type)
select 1,'北京','综合'
union all
select 1,'北京','专业'
union all
select 2,'天津','专业'
union all
select 2,'天津','综合'

select id,name,type=(select type+',' from @tab where id=t.id and name=t.name for xml path('')) from @tab t group by id,name



------解决方案--------------------
create table t(id int ,name varchar(50),type varchar(100))
insert into t
select 1,'北京','综合' union all
select 1,'北京','专业' union all
select 2,'天津','专业' union all
select 2,'天津','综合' union all

select distinct id,name,type=(select ','+type from t b where a.id=b.id and a.name=b.name for xml path('')) from t a

------解决方案--------------------
if object_id('F_Str') is not null 
    drop function F_Str 
go 
create function F_Str(@id int) 
returns nvarchar(100) 
as 
begin 
    declare @S nvarchar(100) 
    select @S=isnull(@S+',','')+type from Tb where id=@id 
    return @S 
end 
go 
Select distinct id,name,type=dbo.F_Str(Col1) from Tb 

go
 
------解决方案--------------------
if object_id('F_Str') is not null 
    drop function F_Str 
go 
create function F_Str(@id int) 
returns nvarchar(100) 
as 
begin 
    declare @S nvarchar(100) 
    select @S=isnull(@S+',','')+type from Tb where id=@id 
    return @S 
end 
go 
Select distinct id,name,type=dbo.F_Str(type) from Tb 
 
go


改成TYPE
------解决方案--------------------
引用: