database - SQLite - 如何获取字符串中所有字符的出现
问题描述
SQLite 中是否有可能从字符串中提取所有字母并计算它们的出现次数?字符串的示例如下所示:“这是一个示例”。
解决方案应如下所示:
字符 -> 出现
T->(1x),h->(1x),i->(2x),s->(2x),a->(2x),e->(2x),x->(1x),m ->(1x),l->(1x)
解决方案
使用递归CTE
:
with
recursive cte as (
select 1 pos, substr('This is an example', 1, 1) letter
union all
select pos + 1, substr('This is an example', pos + 1, 1)
from cte
where pos < length('This is an example')
),
letters as (select distinct letter from cte where letter <> ' ')
select
letter,
length('This is an example') - length(replace('This is an example', letter, '')) counter
from letters
或者:
with
recursive cte as (
select 1 pos, substr('This is an example', 1, 1) letter
union all
select pos + 1, substr('This is an example', pos + 1, 1)
from cte
where pos < length('This is an example')
)
select
letter,
count(*) counter
from cte
where letter <> ' '
group by letter
对于表中的列的情况:
create table tablename(id int, col text);
insert into tablename(id, col) values
(1, 'This is an example'),
(2, 'Another one'),
(3, 'XY');
with
recursive cte as (
select id, col, 1 pos, substr(col, 1, 1) letter
from tablename
union all
select id, col, pos + 1, substr(col, pos + 1, 1)
from cte
where pos < length(col)
)
select
id, col,
letter,
count(*) counter
from cte
where letter <> ' '
group by id, letter;
请参阅演示。
推荐阅读
- javascript - 为什么在另一个锚内动态创建锚时href不起作用?
- c# - 检查 System.Collections.IList 的任何项目是否为空
- macos - 为 wine/heidisql 创建 Mac 启动器脚本的问题
- java - 尽管已初始化 HashMap,但 HashMap.put 方法仍不起作用
- android - Dagger 2 - 构造函数注入 - 非活动
- python - for if 循环根据条件进行分类
- excel - Excel Mac 宏
- python - 无法模拟方法
- python - 游标对象的 MySQL-Python 连接器属性错误
- symfony - 坚持在 onFlush 监听器 symfony