sql 里 怎么把一列的值合并成一个字符串
1、创建测试表,
create table test_str_concat(id varchar2(20), value varchar2(20));
2、插入测试数据
insert into test_str_concat values(1001, 9001);
insert into test_str_concat values(1002, 9002);
insert into test_str_concat values(1003, 9003);
insert into test_str_concat values(1004, 9004);
insert into test_str_concat values(1005, 9005);
commit;
3、查询表中全量数据,select t.*, rowid from test_str_concat t;
4、编写sql,用listagg函数,把value列的数据,拼成一个字符串;
select listagg(value,',') with group(order by id) str from test_str_concat t;拼接后结果为:9001,9002,9003,9004,9005
推荐于2017-09-26 · 知道合伙人软件行家
例表 aaa 合并 a 列
结果为 123 合并
完整语句如下
declare @id nvarchar(20)
declare @id2 nvarchar(20)
declare mycursor cursor for select a from aaa
open mycursor
fetch next from mycursor into @id
set @id2=RTRIM(@id)
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM mycursor into @id
IF @@FETCH_STATUS=0
set @id2=@id2+RTRIM(@id)
END
print @id2
close mycursor
deallocate mycursor