给定字符串中每个字符的计数

时间:2017-02-15 14:52:25

标签: oracle plsql

我需要字符串中每个字符的计数。
示例:

SELECT ('aabcccdee') from dual;  

结果:

a(1),b(2), c(3), d(1),e(2).  

提前致谢。

1 个答案:

答案 0 :(得分:4)

您可以使用分层查询将字符串拆分为单个字符;这是使用CTE来提供您的示例值:

with t (value) as (
  select 'aabcccdee' from dual
)
select substr(value, level, 1) as a_char
from t
connect by level <= length(value);

然后,您可以使用聚合来计算每次出现的次数:

with t (value) as (
  select 'aabcccdee' from dual
)
select a_char, count(*) a_count
from (
  select substr(value, level, 1) as a_char
  from t
  connect by level <= length(value)
)
group by a_char
order by a_char;

A_CH    A_COUNT
---- ----------
a             2
b             1
c             3
d             1
e             2

你可以使用listagg()(如果你是11g或以上)聚合这些字符并计算成一个字符串,如果这是你真正想要的:

with t (value) as (
  select 'aabcccdee' from dual
)
select listagg(a_char || '(' || count(*) || ')', ',') within group (order by a_char)
from (
  select substr(value, level, 1) as a_char
  from t
  connect by level <= length(value)
)
group by a_char;

LISTAGG(A_CHAR||'('||COUNT(*)||')',',')WITHINGROUP(ORDERBYA_CHAR)
-----------------------------------------------------------------
a(2),b(1),c(3),d(1),e(2)

如果您特别想在PL / SQL中执行此操作 - 因为您的值可能已经在PL / SQL变量中 - 您可以使用上下文切换执行相同的操作:

set serveroutput on
declare
  l_value varchar2(30) := 'aabcccdee';
  l_result varchar2(100);
begin
  select listagg(a_char || '(' || count(*) || ')', ',') within group (order by a_char)
  into l_result
  from (
    select substr(l_value, level, 1) as a_char
    from dual
    connect by level <= length(l_value)
  )
  group by a_char;

  dbms_output.put_line(l_result);
end;
/

a(2),b(1),c(3),d(1),e(2)

PL/SQL procedure successfully completed.