本文小編為大家詳細(xì)介紹“SQL怎么按某字段合并字符串”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“SQL怎么按某字段合并字符串”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。
創(chuàng)新互聯(lián)于2013年創(chuàng)立,先為竹山等服務(wù)建站,竹山等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為竹山企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。
標(biāo)題:按某字段合并字符串之一(簡單合并)
描述:將如下形式的數(shù)據(jù)按id字段合并value字段。id value----- ------1 aa1 bb2 aaa2 bbb2 ccc需要得到結(jié)果:id value------ -----------1 aa,bb2 aaa,bbb,ccc即:group by id, 求 value 的和(字符串相加)
1、sql2000中只能用自定義的函數(shù)解決
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--調(diào)用函數(shù)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、使用游標(biāo)合并數(shù)據(jù)
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))--定義結(jié)果集表變量--定義游標(biāo)并進(jìn)行合并處理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怎么按某字段合并字符串”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。