欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Oracle 多行记录合并/连接/聚合字符串的几种方法

程序员文章站 2023-12-05 07:58:45
什么是合并多行字符串(连接字符串)呢,例如: sql> desc test; name type nullable default comments -------...
什么是合并多行字符串(连接字符串)呢,例如:
sql> desc test;
name type nullable default comments
------- ------------ -------- ------- --------
country varchar2(20) y
city varchar2(20) y

sql> select * from test;


country city
-------------------- --------------------
中国 台北
中国 香港
中国 上海
日本 东京
日本 大阪
要求得到如下结果集:
------- --------------------
中国 台北,香港,上海
日本 东京,大阪
实际就是对字符实现一个聚合功能,我很奇怪为什么oracle没有提供官方的聚合函数来实现它呢:)
下面就对几种经常提及的解决方案进行分析(有一个评测标准最高★★★★★):
1.被集合字段范围小且固定型 灵活性★ 性能★★★★ 难度 ★
这种方法的原理在于你已经知道city字段的值有几种,且还不算太多,如果太多这个sql就会相当的长。。看例子:
sql> select t.country,
2 max(decode(t.city,'台北',t.city||',',null)) ||
3 max(decode(t.city,'香港',t.city||',',null))||
4 max(decode(t.city,'上海',t.city||',',null))||
5 max(decode(t.city,'东京',t.city||',',null))||
6 max(decode(t.city,'大阪',t.city||',',null))
7 from test t group by t.country
8 /


country max(decode(t.city,'台北',t.cit
-------------------- ------------------------------
中国 台北,香港,上海,
日本 东京,大阪,
大家一看,估计就明白了(如果不明白,好好补习max decode和分组)。这种方法无愧为最笨的方法,但是对某些应用来说,最有效的方法也许就是它。
2.固定表固定字段函数法 灵活性★★ 性能★★★★ 难度 ★★
此法必须预先知道是哪个表,也就是说一个表就得写一个函数,不过方法1的一个取值就要便捷多了。在大多数应用中,也不会存在大量这种合并字符串的需求。废话完毕,看下面:
定义一个函数
create or replace function str_list( str_in in varchar2 )--分类字段
return varchar2
is
str_list varchar2(4000) default null;--连接后字符串
str varchar2(20) default null;--连接符号
begin
for x in ( select test.city from test where test.country = str_in ) loop
str_list := str_list || str || to_char(x.city);
str := ', ';
end loop;
return str_list;
end;
使用:
sql> select distinct(t.country),list_func1(t.country) from test t;

country list_func1(t.country)
-------------------- ----------------
中国 台北, 香港, 上海
日本 东京, 大阪

sql> select t.country,str_list(t.country) from test t group by t.country;


country str_list(t.country)
-------------------- -----------------------
中国 台北, 香港, 上海
日本 东京, 大阪
这个时候,使用分组和求唯一都可以满足要求。它的原理就是,根据唯一的分组字段country,在函数里面再次查询该字段对应的所有被合并列,使用pl/sql将其合并输出。
3.灵活表函数法 灵活性★★★ 性能★★★ 难度 ★★★
该方法是在方法2的基础上,使用动态sql,将表名和字段名称传入,从而达到灵活的目的。
create or replace function str_list2( key_name in varchar2,
key in varchar2,
coname in varchar2,
tname in varchar2 )
return varchar2
as
type rc is ref cursor;
str varchar2(4000);
sep varchar2(2);
val varchar2(4000);
cur rc;
begin
open cur for 'select '||coname||'
from '|| tname || '
where ' || key_name || ' = :x '
using key;
loop
fetch cur into val;
exit when cur%notfound;
str := str || sep || val;
sep := ', ';
end loop;
close cur;
return str;
end;
sql> select test.country,
2 str_list2('country', test.country, 'city', 'test') emplist
3 from test
4 group by test.country
5 /


country emplist
-------------------- -----------------
中国 台北, 香港, 上海
日本 东京, 大阪
4.一条sql法 灵活性★★★★ 性能★★ 难度 ★★★★
一条sql的法则是某位大师提出的,大家曾经在某个时期都乐此不彼的寻求各种的问题一条sql法,但是大师的意思似乎被曲解,很多性能差,可读性差,灵活差的sql都是这个原则产物,所谓画虎不成反成犬类。不过,解决问题始终是第一原则,这里还是给出一个比较有代表性的一条sql方法。
select country,max(substr(city,2)) city
from
(select country,sys_connect_by_path(city,',') city
from
(select country,city,country||rn rchild,country||(rn-1) rfather
from
(select test.country ,test.city,row_number() over (partition by test.country order by test.city) rn from test))
connect by prior rchild=rfather start with rfather like '%0')
group by country;
下面分步解析,有4个from,就有4次结果集的操作。
step 1 给记录加上序号rn
sql> select test.country ,test.city,row_number() over (partition by test.country order by test.city) rn
2 from test
3 /


country city rn
-------------------- -------------------- ----------
日本 大阪 1
日本 东京 2
中国 上海 1
中国 台北 2
中国 香港 3
step 2 创造子节点父节点
sql> select country,city,country||rn rchild,country||(rn-1) rfather
2 from
3 (select test.country ,test.city,row_number() over (partition by test.country order by test.city) rn
4 from test)
5 /
日本 大阪 日本1 日本0
日本 东京 日本2 日本1
中国 上海 中国1 中国0
中国 台北 中国2 中国1
中国 香港 中国3 中国2
step 3 利用sys_connect_by_path生成结果集
select country,sys_connect_by_path(city,',') city
from
(select country,city,country||rn rchild,country||(rn-1) rfather
from
(select test.country ,test.city,row_number() over (partition by test.country order by test.city) rn from test)) connect by prior rchild=rfather start with rfather like '%0'
日本 ,大阪
日本 ,大阪,东京
中国 ,上海
中国 ,上海,台北
中国 ,上海,台北,香港
step 4 最终步骤,筛选结果集合
sql> select country,max(substr(city,2)) city
2 from
3 (select country,sys_connect_by_path(city,',') city
4 from
5 (select country,city,country||rn rchild,country||(rn-1) rfather
6 from
7 (select test.country ,test.city,row_number() over (partition by test.country order by test.city) rn
8 from test))
9 connect by prior rchild=rfather start with rfather like '%0')
10 group by country;


country city
-------------------- -------
中国 上海,台北,香港
日本 大阪,东京


可谓是,7歪8搞,最后还是弄出来了,呵呵。 ps:(逻辑上是对的..但是写的比较繁琐,可以简化!)
5.自定义聚合函数 灵活性★★★★★ 性能★★★★★ 难度 ★★★★★
最后一个方法是我认为“王道”的方法,自定义聚合函数。
就如何我在本开始说的,为啥oracle没有这种聚合函数呢?我也不知道,但oracle提供了聚合函数的api可以让我方便的自己定义聚合函数。
详细可以看oracle data catridge guide这个文档。连接如下:
http://www.oracle.com.cn/other/9ionlinedoc/appdev.920/a96595/toc.htm
下面给出一个简单的例子:
sql> select t.country,strcat(t.city) from test t group by t.country;


country strcat(t.city)
-------------------- ------------------
日本 东京,大阪
中国 台北,香港,上海
简单吧,和官方的函数一样的便捷高效。
函数:
create or replace function strcat(input varchar2 )
return varchar2
parallel_enable aggregate using strcat_type;
type:
create or replace type strcat_type as object (
cat_string varchar2(4000),
static function odciaggregateinitialize(cs_ctx in out strcat_type) return number,
member function odciaggregateiterate(self in out strcat_type,value in varchar2) return number,
member function odciaggregatemerge(self in out strcat_type,ctx2 in out strcat_type) return number,member function odciaggregateterminate(self in out strcat_type,returnvalue out
varchar2,flags in number) return number)
6.待发掘...

ps: 在 oracle 10g下,可以使用以下系统函数:
select id,wmsys.wm_concat(oid) oid
from table1
group by id
总结,合并字符串还有更多的方法希望大家能发掘,本文的目的主要是抛砖引玉,如果有新的发现我会继续更新方法。需要注意的问题是,本文采用varchar2为例子,所以长度有限制,oracle的版本对方法的实现也影响。