共計 2029 個字符,預計需要花費 6 分鐘才能閱讀完成。
本文丸趣 TV 小編為大家詳細介紹“SQL 怎么按某字段合并字符串”,內容詳細,步驟清晰,細節處理妥當,希望這篇“SQL 怎么按某字段合并字符串”文章能幫助大家解決疑惑,下面跟著丸趣 TV 小編的思路慢慢深入,一起來學習新知識吧。
標題:按某字段合并字符串之一 (簡單合并)
描述:將如下形式的數據按 id 字段合并 value 字段。id value—– ——1 aa1 bb2 aaa2 bbb2 ccc 需要得到結果:id value—— ———–1 aa,bb2 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)gocreate function dbo.f_str(@id int) returns varchar(100)asbegin declare @str varchar(1000) set @str= select @str=@str+ +cast(value as varchar) from tb where id = @id set @str=right(@str , len(@str) - 1) return @strendgo-- 調用函數 select id , value = dbo.f_str(id) from tb group by iddrop function dbo.f_strdrop 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)goselect id, [value] = stuff((select , + [value] from tb t where id = tb.id for xml path()) , 1 , 1 , )from tb group by iddrop table tb
3、使用游標合并數據
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)godeclare @t table(id int,value varchar(100))-- 定義結果集表變量 -- 定義游標并進行合并處理 declare my_cursor cursor local forselect id , value from tbdeclare @id_old int , @id int , @value varchar(10) , @s varchar(100)open my_cursor fetch my_cursor into @id , @valueselect @id_old = @id , @s= while @@FETCH_STATUS = 0begin if @id = @id_old select @s = @s + , + cast(@value as varchar) else begin insert @t values(@id_old , stuff(@s,1,1,)) select @s = , + cast(@value as varchar) , @id_old = @id end fetch my_cursor into @id , @value END insert @t values(@id_old , stuff(@s,1,1,)) close my_cursor deallocate my_cursor select * from @tdrop table tb
讀到這里,這篇“SQL 怎么按某字段合并字符串”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注丸趣 TV 行業資訊頻道。
正文完