读书人

表中两个字段相同怎么删除重复的字段

发布时间: 2013-11-23 10:52:51 作者: rapoo

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

一张表里面以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
[解决办法]
引用:
Quote: 引用:

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

谢谢版主,列名 'Col1' 无效怎么办?


Col1 就是要传的列名。
Select distinct id,name,type=dbo.F_Str(id) from Tb

读书人网 >SQL Server

热点推荐