CSDNの字串合并

來源:互聯網
上載者:User

描述:將如下形式的資料按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

isnull(expression ,value) --處理null值,如果expression為nulll,返回value    
select cast('123' as int) --類型轉化, 將字元123轉化為int型

 

PS:http://topic.csdn.net/u/20110316/20/564bd00d-7edb-4386-b205-2f0186930130.html?79115

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.