国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > SQL Server > 正文

分組字符合并SQL語句 按某字段合并字符串之一(簡單合并)

2024-08-31 01:04:40
字體:
來源:轉載
供稿:網友

標題:按某字段合并字符串之一(簡單合并)


描述:將如下形式的數據按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')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語句的介紹。希望對大家有所幫助。

 

注:相關教程知識閱讀請移步到MSSQL教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 虞城县| 开鲁县| 十堰市| 益阳市| 张家口市| 班玛县| 宜兰市| 渑池县| 涿州市| 巴南区| 宁海县| 绥宁县| 云浮市| 云安县| 建瓯市| 荥阳市| 扬中市| 佳木斯市| 泸溪县| 富蕴县| 清新县| 行唐县| 长宁区| 钟山县| 阳高县| 韶关市| 澄江县| 固阳县| 枝江市| 象州县| 宁国市| 密云县| 沛县| 通州市| 南投县| 无棣县| 多伦县| 色达县| 灵丘县| 肃北| 辉南县|