我需要字符串中每个字符的数量。
实施例:给定字符串中每个字符的数量
SELECT ('aabcccdee') from dual;
结果:
a(1),b(2), c(3), d(1),e(2).
预先感谢。
我需要字符串中每个字符的数量。
实施例:给定字符串中每个字符的数量
SELECT ('aabcccdee') from dual;
结果:
a(1),b(2), c(3), d(1),e(2).
预先感谢。
您可以使用分层查询将字符串拆分为单个字符;这是一个使用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 - 因为你重视我s已经在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.
考虑到额外需求,查看构建查询的方式非常好。 – BriteSponge
这真棒Alex。你没有给任何人回答任何其他方式的空间。 +1 – XING
它通常被认为很好,可以显示你已经尝试或研究过的东西。 http://stackoverflow.com/help/how-to-ask – BriteSponge