22,209
社区成员
发帖
与我相关
我的任务
分享
/*
标题:按某字段合并字符串之一(简单合并)
作者:爱新觉罗.毓华(十八年风雨,守得冰山雪莲花开)
时间:2008-11-06
地点:广东深圳
描述:将如下形式的数据按id字段合并value字段。
id value
----- ------
1 aa
1 bb
2 aaa
2 bbb
2 ccc
需要得到结果:
id value
------ -----------
1 aa,bb
2 aaa,bbb,ccc
即:group by id, 求 value 的和(字符串相加)
*/
--1、sql2000中只能用自定义的函数解决
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 dbo.f_str(@id varchar(10)) returns varchar(1000)
as
begin
declare @str varchar(1000)
select @str = isnull(@str + ',' , '') + cast(value as varchar) from tb where id = @id
return @str
end
go
--调用函数
select id , value = dbo.f_str(id) from tb group by id
drop function dbo.f_str
drop table tb
--2、sql2005中的方法
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 id, [value] = stuff((select ',' + [value] from tb t where id = tb.id for xml path('')) , 1 , 1 , '')
from tb
group by id
drop table tb
create table tb(BssID int, BtsID int)
insert into tb values(1 ,6)
insert into tb values(1 ,7)
insert into tb values(1 ,9)
insert into tb values(1 ,12)
insert into tb values(1 ,13)
insert into tb values(1 ,15)
insert into tb values(2 ,12)
insert into tb values(2 ,23)
insert into tb values(2 ,45)
insert into tb values(2 ,67)
insert into tb values(2 ,12)
insert into tb values(2 ,45)
go
create function dbo.f_str(@BssID int,@px int) returns varchar(1000)
as
begin
declare @str varchar(1000)
select @str = isnull(@str + ',' , '') + cast(BtsID as varchar) from (select t.* , px = (((select count(1) from tb where BssID = t.BssID and BtsID < t.BtsID) + 1) - 1)/2 from tb t ) m where BssID = @BssID and px = @px
return @str
end
go
--调用函数
select BssID , BtsID = dbo.f_str(BssID,px) from (select t.* , px = (((select count(1) from tb where BssID = t.BssID and BtsID < t.BtsID) + 1) - 1)/2 from tb t ) m group by BssID , px
drop function dbo.f_str
drop table tb
/*
BssID BtsID
----------- ---------
1 6,7
1 9,12
1 13,15
2 12,12
2 23,45,45
2 67
(所影响的行数为 6 行)
*/
--> 测试数据: tb
if object_id('tb') is not null drop table tb
go
create table tb (BssID int,BtsID int)
insert into tb
select 1,6 union all
select 1,7 union all
select 1,9 union all
select 1,12 union all
select 1,13 union all
select 1,15 union all
select 2,12 union all
select 2,23 union all
select 2,45 union all
select 2,67 union all
select 2,12 union all
select 2,45
;with szy as
(
select *,pm=row_number()over (partition by BssID order by getdate())
from tb
)
select a.BssID,BtsID=ltrim(a.BtsID)+','+ltrim(b.BtsID)
from szy a,szy b
where a.pm+1=b.pm and a.pm%2=1 and b.pm%2=0 and a.BssID=b.BssID
order by a.BssID
BssID BtsID
----------- -------------------------
1 6,7
1 9,12
1 13,15
2 12,23
2 45,67
2 12,45
(6 行受影响)