在sql列中查找最常用的单词(包含多个单词)

2024-05-13 05:43:08 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我在sqlite3中有这个列:

hello world
hello you two
hello world
hello hello

我想提取最流行的单词及其出现的次数。 然而,直到现在,似乎只有找到细胞的存在才有可能。像这样:

SELECT titles, COUNT(titles) 
FROM standart_results
GROUP BY titles
ORDER BY count(*) DESC

它将返回("hello world", 2)。 但是我想要("hello", 5)

我也不能用LIKE,因为我不知道哪个词出现得最多

我是否需要将数据传输到一个变量中并在其上使用regex,或者我可以使用sql来完成


Tags: fromyouhelloworldbycount单词次数
2条回答

SQLite没有很好的字符串处理能力,也没有返回表的方法。但是,它确实支持递归CTE。您可以使用此结构将标题拆分为单词:

with recursive cte as (
      select null as word, title || ' ' as rest, 0 as lev
      from t
      union all
      select substr(rest, 1, instr(rest, ' ') - 1) as word, 
             substr(rest, instr(rest, ' ') + 1) rest,
             lev + 1
      from cte
      where lev < 5 and rest like '% %'
     )
select word, count(*)
from cte
where word is not null
group by word;

Here是一个db<&燃气轮机;小提琴

要获取最上面的单词,您可以使用:

select word, count(*)
from cte
where word is not null
group by word
order by count(*) desc
limit 1;

你可以试试这个

SELECT titles, COUNT(titles) as Appearances
FROM standart_results
GROUP BY titles
ORDER BY Appearances DESC LIMIT 1

相关问题 更多 >