有如下表
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([name] varchar(50),sn varchar(5000))
insert [tb]
select '联想手机红色','123456789' union all
select '联想手机红色','100006789' union all
select '联想手机红色','123336789' union all
select '海尔手机黑色A货','234532390' union all
select '海尔手机黑色A货','234568878' union all
select '索尼手机灰色B货','345678901'select * from tb我想得到这个结果,以NAME字段分组,SN字段用空格合并,不知能不能这样查
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([name] varchar(50),sn varchar(5000))
insert [tb]
select '三星电脑红色','123456789 100006789 123336789' union all
select '海尔电脑黑色A货','234532390 234568878' union all
select '索尼电脑灰色B货','345678901'select * from tb
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([name] varchar(50),sn varchar(5000))
insert [tb]
select '联想手机红色','123456789' union all
select '联想手机红色','100006789' union all
select '联想手机红色','123336789' union all
select '海尔手机黑色A货','234532390' union all
select '海尔手机黑色A货','234568878' union all
select '索尼手机灰色B货','345678901'select * from tb我想得到这个结果,以NAME字段分组,SN字段用空格合并,不知能不能这样查
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([name] varchar(50),sn varchar(5000))
insert [tb]
select '三星电脑红色','123456789 100006789 123336789' union all
select '海尔电脑黑色A货','234532390 234568878' union all
select '索尼电脑灰色B货','345678901'select * from tb
RETURNS NVARCHAR(40)
AS
BEGIN
DECLARE @RESULT NVARCHAR(40)
SELECT @RESULT=ISNULL(@RESULT+',','')+a FROM A WHERE c2=@c
RETURN @RESULT
END
if object_id('tb') is not null drop table tb
create table tb([name] varchar(50),sn varchar(5000))
insert into tb
select '联想手机红色', 123456789 union all
select '联想手机红色', 100006789 union all
select '联想手机红色', 123336789 union all
select '海尔手机黑色A货', 234532390 union all
select '海尔手机黑色A货', 234568878 union all
select '索尼手机灰色B货', 345678901
go--> SQL Server 2005select name, sn = stuff((select ' ' + rtrim(sn) as [text()] from tb where name = a.name for xml path('')) , 1, 1, '') from tb as a group by name
/*
name sn
--------------- -----------------------------
海尔手机黑色A货 234532390 234568878
联想手机红色 123456789 100006789 123336789
索尼手机灰色B货 345678901
*/
go--> SQL Server 2000 自定义字符串合并函数create function fn_tb_sn (@name varchar(15))
returns varchar(8000)
as
begin
declare @str varchar(8000)
select @str = isnull(@str + ' ', '') + rtrim(sn) from tb where name = @name
return(@str)
end
go--> SQL Server 2000 调用自定义函数合并字符串
select name, sn = dbo.fn_tb_sn(name) from tb group by name
/*
name sn
--------------- -----------------------------
海尔手机黑色A货 234532390 234568878
联想手机红色 123456789 100006789 123336789
索尼手机灰色B货 345678901
*/--> 删除测试
drop function fn_tb_sn
drop table tb