【SQL精彩語句】合併列值

--合併列值
--
原著:鄒建
--
改編:愛新覺羅.毓華(十八年風雨,守得冰山雪蓮花開)  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')
go

create 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 id

drop 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 tb

drop 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中的方法
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, [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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章