合并列值 原著:邹建 改编:爱新觉罗.毓华 2007-12-16 广东深圳表结构,数据如下: id value ----- ------ 1 aa 1 bb 2 aaa 2 bbb 2 ccc需要得到结果: id values ------ ----------- 1 aa,bb 2 aaa,bbb,ccc 即:group by id, 求 value 的和(字符串相加)1. 旧的解决方法(在sql server 2000中只能用函数解决。) --1. 创建处理函数 create table tb(id int, value varchar(10)) insert into tb values(1, 'aa') insert into tb values(1, 'bb') insert into tb values(2, 'aaa') insert into tb values(2, 'bbb') insert into tb values(2, 'ccc') goCREATE FUNCTION dbo.f_str(@id int) RETURNS varchar(8000) AS BEGIN DECLARE @r varchar(8000) SET @r = '' SELECT @r = @r + ',' + value FROM tb WHERE id=@id RETURN STUFF(@r, 1, 1, '') END GO-- 调用函数 SELECt id, value = dbo.f_str(id) FROM tb GROUP BY iddrop table tb drop function dbo.f_str/* id value ----------- ----------- 1 aa,bb 2 aaa,bbb,ccc (所影响的行数为 2 行) */--2、另外一种函数. create table tb(id int, value varchar(10)) insert into tb values(1, 'aa') insert into tb values(1, 'bb') insert into tb values(2, 'aaa') insert into tb values(2, 'bbb') insert into tb values(2, 'ccc') go--创建一个合并的函数 create function f_hb(@id int) returns varchar(8000) as begin declare @str varchar(8000) set @str = '' select @str = @str + ',' + cast(value as varchar) from tb where id = @id set @str = right(@str , len(@str) - 1) return(@str) End go--调用自定义函数得到结果: select distinct id ,dbo.f_hb(id) as value from tbdrop table tb drop function dbo.f_hb/* id value ----------- ----------- 1 aa,bb 2 aaa,bbb,ccc (所影响的行数为 2 行) */2. 新的解决方法(在sql server 2005中用OUTER APPLY等解决。) create table tb(id int, value varchar(10)) insert into tb values(1, 'aa') insert into tb values(1, 'bb') insert into tb values(2, 'aaa') insert into tb values(2, 'bbb') insert into tb values(2, 'ccc') go -- 查询处理 SELECT * FROM(SELECT DISTINCT id FROM tb)A OUTER APPLY( SELECT [values]= STUFF(REPLACE(REPLACE( ( SELECT value FROM tb N WHERE id = A.id FOR XML AUTO ), '<N value="', ','), '"/>', ''), 1, 1, '') )N drop table tb/* id values ----------- ----------- 1 aa,bb 2 aaa,bbb,ccc(2 行受影响) */--SQL2005中的方法2(csdn dobear_0922 提供) create table tb(id int, value varchar(10)) insert into tb values(1, 'aa') insert into tb values(1, 'bb') insert into tb values(2, 'aaa') insert into tb values(2, 'bbb') insert into tb values(2, 'ccc') goselect id, [values]=stuff((select ','+[value] from tb t where id=tb.id for xml path('')), 1, 1, '') from tb group by id/* id values ----------- -------------------- 1 aa,bb 2 aaa,bbb,ccc(2 row(s) affected)*/drop table tb
/* -- Author:Flystone -- Version:V1.001 Date:2008-05-15 初稿 -- Version:V1.002 Date:2008-05-16 1、 处理空格带来的异常 -- 2、 增加了形如yyyy-mm-dd hh:mm:ss -- yyyy-m-d h:m:s 格式的处理 */-- Test Data: ta If object_id('ta') is not null Drop table ta Go Create table ta(id1 int,id2 varchar(1)) Go Insert into ta select 1,'a' union all select 1,'b' union all select 1,'c' union all select 2,'b' union all select 2,'e' Go --Start create function f_str(@id int) returns varchar(8000) as begin declare @s varchar(8000) select @s = isnull(@s+',','')+ id2 from ta where id1 = @id return @s end go select id1,dbo.f_str(id1) as id2 from ta group by id1 --Result: /*id1 id2 ----------- ------ 1 a,b,c 2 b,e(所影响的行数为 2 行) */ --End
use test go --> --> (Roy_88)生成測試數據
if not object_id('Tempdb..#T') is null drop table #T Go Create table #T([id1] int,[id2] nvarchar(1)) Insert #T select 1,'a' union all select 1,'b' union all select 1,'c' union all select 2,'b' union all select 2,'e' GoSELECT [id1] = a.[id1], [id2] = C.column_names.value('/c[1]', 'nvarchar(max)') from (SELECT distinct [id1] FROM #T)a CROSS APPLY( SELECT column_names = ( SELECT [id2] FROM #T c WHERE [id1] = a.[id1] FOR XML AUTO, TYPE ).query('<c> {for $i in /c[position()<last()]/@id2 return concat(string($i),",")} {concat(" ",string(/c[last()]/@id2))} </c>') )C/* (5 行受影响) id1 id2 ----------- --------------- 1 a, b, c 2 b, e(2 行受影响)*/
Use Test go Declare @1 Table(id1 int,id2 char(1)) Insert Into @1 Select 1 ,'a' Union All Select 1 ,'b' Union All Select 1 ,'c' Union All Select 2 ,'b' Union All Select 2 ,'e'Select * From (Select Distinct id1 From @1) a Cross Apply( Select id2=Stuff((Select ','+id2 From @1 b where b.id1=a.id1 For Xml path('')),1,1,'') ) d--Or Select id1, id2=Stuff((Select ','+id2 From @1 b where b.id1=a.id1 For Xml path('')),1,1,'') From @1 a Group By id1/* id1 id2 -------------------------- 1 a,b,c 2 b,e */
if object_id('tb') is not null drop table tb if object_id('f_get') is not null drop function f_get go create table tb(id1 int,id2 char(2)) insert into tb select 1, 'a' union all select 1, 'b' union all select 1, 'c' union all select 2, 'b' union all select 2, 'e' go create function f_get (@id1 int) returns varchar(10) as begin declare @s varchar(10) select @s=isnull(@s,'')+id2+',' from tb where id1=@id1 return substring(@s,1,len(@s)-1) end goselect distinct id1,dbo.f_get(id1) as id2 from tb -- 绝对正确 接分
decimal @a table ( id1 int, id2 nvarchar(6) ) insert into @a select 1,id2 union all select 1,'b' union all select 1,'c' union all select 2,'b' union all select 2,'e' select top1 a.id1,'a'+','+ 'b' + ',' + 'c' from @a a union all select top1 a.id2,'b'+',' + 'c' from @a a order by a.id2 desc
id1 id2 1 a,b,c 2 b,c
set nocount on if object_id('ta') is not null drop table ta create table ta (ID int, col varchar(10)) insert into ta select 1,'a' union all select 1,'b' union all select 1,'c' union all select 2,'b' union all select 2,'e' go create function f_combine (@ID int) returns varchar(800) as begin declare @c varchar(800) select @c=isnull(@c+',','')+col from ta where ID=@ID return @c end go select distinct ID,dbo.f_combine(ID) from ta go drop function dbo.f_combine drop table ta set nocount off
原著:邹建
改编:爱新觉罗.毓华 2007-12-16 广东深圳表结构,数据如下:
id value
----- ------
1 aa
1 bb
2 aaa
2 bbb
2 ccc需要得到结果:
id values
------ -----------
1 aa,bb
2 aaa,bbb,ccc
即:group by id, 求 value 的和(字符串相加)1. 旧的解决方法(在sql server 2000中只能用函数解决。)
--1. 创建处理函数
create table tb(id int, value varchar(10))
insert into tb values(1, 'aa')
insert into tb values(1, 'bb')
insert into tb values(2, 'aaa')
insert into tb values(2, 'bbb')
insert into tb values(2, 'ccc')
goCREATE FUNCTION dbo.f_str(@id int)
RETURNS varchar(8000)
AS
BEGIN
DECLARE @r varchar(8000)
SET @r = ''
SELECT @r = @r + ',' + value FROM tb WHERE id=@id
RETURN STUFF(@r, 1, 1, '')
END
GO-- 调用函数
SELECt id, value = dbo.f_str(id) FROM tb GROUP BY iddrop table tb
drop function dbo.f_str/*
id value
----------- -----------
1 aa,bb
2 aaa,bbb,ccc
(所影响的行数为 2 行)
*/--2、另外一种函数.
create table tb(id int, value varchar(10))
insert into tb values(1, 'aa')
insert into tb values(1, 'bb')
insert into tb values(2, 'aaa')
insert into tb values(2, 'bbb')
insert into tb values(2, 'ccc')
go--创建一个合并的函数
create function f_hb(@id int)
returns varchar(8000)
as
begin
declare @str varchar(8000)
set @str = ''
select @str = @str + ',' + cast(value as varchar) from tb where id = @id
set @str = right(@str , len(@str) - 1)
return(@str)
End
go--调用自定义函数得到结果:
select distinct id ,dbo.f_hb(id) as value from tbdrop table tb
drop function dbo.f_hb/*
id value
----------- -----------
1 aa,bb
2 aaa,bbb,ccc
(所影响的行数为 2 行)
*/2. 新的解决方法(在sql server 2005中用OUTER APPLY等解决。)
create table tb(id int, value varchar(10))
insert into tb values(1, 'aa')
insert into tb values(1, 'bb')
insert into tb values(2, 'aaa')
insert into tb values(2, 'bbb')
insert into tb values(2, 'ccc')
go
-- 查询处理
SELECT * FROM(SELECT DISTINCT id FROM tb)A OUTER APPLY(
SELECT [values]= STUFF(REPLACE(REPLACE(
(
SELECT value FROM tb N
WHERE id = A.id
FOR XML AUTO
), '<N value="', ','), '"/>', ''), 1, 1, '')
)N
drop table tb/*
id values
----------- -----------
1 aa,bb
2 aaa,bbb,ccc(2 行受影响)
*/--SQL2005中的方法2(csdn dobear_0922 提供)
create table tb(id int, value varchar(10))
insert into tb values(1, 'aa')
insert into tb values(1, 'bb')
insert into tb values(2, 'aaa')
insert into tb values(2, 'bbb')
insert into tb values(2, 'ccc')
goselect id, [values]=stuff((select ','+[value] from tb t where id=tb.id for xml path('')), 1, 1, '')
from tb
group by id/*
id values
----------- --------------------
1 aa,bb
2 aaa,bbb,ccc(2 row(s) affected)*/drop table tb
/*
-- Author:Flystone
-- Version:V1.001 Date:2008-05-15 初稿
-- Version:V1.002 Date:2008-05-16 1、 处理空格带来的异常
-- 2、 增加了形如yyyy-mm-dd hh:mm:ss
-- yyyy-m-d h:m:s 格式的处理
*/-- Test Data: ta
If object_id('ta') is not null
Drop table ta
Go
Create table ta(id1 int,id2 varchar(1))
Go
Insert into ta
select 1,'a' union all
select 1,'b' union all
select 1,'c' union all
select 2,'b' union all
select 2,'e'
Go
--Start
create function f_str(@id int)
returns varchar(8000)
as
begin
declare @s varchar(8000)
select @s = isnull(@s+',','')+ id2 from ta where id1 = @id
return @s
end
go
select id1,dbo.f_str(id1) as id2
from ta
group by id1
--Result:
/*id1 id2
----------- ------
1 a,b,c
2 b,e(所影响的行数为 2 行)
*/
--End
go
--> --> (Roy_88)生成測試數據
if not object_id('Tempdb..#T') is null
drop table #T
Go
Create table #T([id1] int,[id2] nvarchar(1))
Insert #T
select 1,'a' union all
select 1,'b' union all
select 1,'c' union all
select 2,'b' union all
select 2,'e'
GoSELECT
[id1] = a.[id1],
[id2] = C.column_names.value('/c[1]', 'nvarchar(max)')
from
(SELECT distinct [id1] FROM #T)a
CROSS APPLY(
SELECT column_names = (
SELECT [id2]
FROM #T c
WHERE [id1] = a.[id1]
FOR XML AUTO, TYPE
).query('<c>
{for $i in /c[position()<last()]/@id2 return concat(string($i),",")}
{concat(" ",string(/c[last()]/@id2))}
</c>')
)C/*
(5 行受影响)
id1 id2
----------- ---------------
1 a, b, c
2 b, e(2 行受影响)*/
Use Test
go
Declare @1 Table(id1 int,id2 char(1))
Insert Into @1
Select 1 ,'a' Union All
Select 1 ,'b' Union All
Select 1 ,'c' Union All
Select 2 ,'b' Union All
Select 2 ,'e'Select *
From (Select Distinct id1 From @1) a
Cross Apply(
Select id2=Stuff((Select ','+id2 From @1 b where b.id1=a.id1 For Xml path('')),1,1,'')
) d--Or
Select
id1,
id2=Stuff((Select ','+id2 From @1 b where b.id1=a.id1 For Xml path('')),1,1,'')
From @1 a
Group By id1/*
id1 id2
--------------------------
1 a,b,c
2 b,e
*/
drop table tb
if object_id('f_get') is not null
drop function f_get
go
create table tb(id1 int,id2 char(2))
insert into tb
select 1, 'a' union all
select 1, 'b' union all
select 1, 'c' union all
select 2, 'b' union all
select 2, 'e'
go
create function f_get
(@id1 int)
returns varchar(10)
as
begin
declare @s varchar(10)
select @s=isnull(@s,'')+id2+',' from tb where id1=@id1
return substring(@s,1,len(@s)-1)
end
goselect distinct id1,dbo.f_get(id1) as id2 from tb
--
绝对正确 接分
decimal @a table
( id1 int,
id2 nvarchar(6)
)
insert into @a select 1,id2
union all select 1,'b'
union all select 1,'c'
union all select 2,'b'
union all select 2,'e'
select top1 a.id1,'a'+','+ 'b' + ',' + 'c' from @a a
union all
select top1 a.id2,'b'+',' + 'c' from @a a order by a.id2 desc
id1 id2
1 a,b,c
2 b,c
if object_id('ta') is not null drop table ta
create table ta (ID int, col varchar(10))
insert into ta select 1,'a'
union all select 1,'b'
union all select 1,'c'
union all select 2,'b'
union all select 2,'e'
go
create function f_combine (@ID int)
returns varchar(800)
as
begin
declare @c varchar(800)
select @c=isnull(@c+',','')+col from ta where ID=@ID
return @c
end
go
select distinct ID,dbo.f_combine(ID) from ta
go
drop function dbo.f_combine
drop table ta
set nocount off