如何在Oracle中将多行合并为逗号分隔的列表?我有一个简单的查询:select * from countries取得了以下结果:country_name------------Albania
Andorra
Antigua.....我想在一行中返回结果,如下所示:Albania, Andorra, Antigua, ...当然,我可以编写一个PL/SQL函数来完成这项工作(我已经在Oracle 10g中这样做了),但是是否有一个更好的、最好是非Oracle特定的解决方案(或者可能是一个内置函数)来完成这项任务?我通常会使用它来避免子查询中的多行,所以如果一个人有一个以上的公民身份,我不希望她/他在列表中重复。我的问题是基于类似的问题SQL Server 2005.更新*我的功能如下:CREATE OR REPLACE FUNCTION APPEND_FIELD (sqlstr in varchar2, sep in varchar2 ) return varchar2 isret varchar2(4000) := '';TYPE cur_typ IS REF CURSOR;rec cur_typ;field varchar2(4000);begin
OPEN rec FOR sqlstr;
LOOP FETCH rec INTO field;
EXIT WHEN rec%NOTFOUND;
ret := ret || field || sep;
END LOOP;
if length(ret) = 0 then
RETURN '';
else
RETURN substr(ret,1,length(ret)-length(sep));
end if;end;
3 回答
潇湘沐
TA贡献1816条经验 获得超6个赞
create table countries ( country_name varchar2 (100));insert into countries values ('Albania');insert into countries values ('Andorra');insert into countries values ('Antigua');SELECT SUBSTR (SYS_CONNECT_BY_PATH (country_name , ','), 2) csv FROM (SELECT country_name , ROW_NUMBER () OVER (ORDER BY country_name ) rn, COUNT (*) OVER () cnt FROM countries) WHERE rn = cntSTART WITH rn = 1CONNECT BY rn = PRIOR rn + 1;CSV --------------------------Albania,Andorra,Antigua 1 row selected.
select listagg(country_name,', ') within group(order by country_name) csv from countries;CSV --------------------------Albania, Andorra, Antigua1 row selected.
添加回答
举报
0/150
提交
取消