【问题标题】:Find the most common word in a sql column (with multiple words)查找一个sql列中最常用的词(有多个词)
【发布时间】:2021-06-11 05:36:30
【问题描述】:

比如我在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,因为我不知道哪个词出现的次数最多。

我需要将数据传输到变量中并在其上使用正则表达式还是可以使用 sql 来完成?

【问题讨论】:

  • 你可以使用split()标签吗?
  • 是的,但为此我必须将所有数据传输到 python 变量中,这会减慢我的速度。如果可能,我会直接从 sqlite 中选择所有数据
  • 这能回答你的问题吗? How to split comma-separated value in SQLite?
  • 只需用空格替换 , 上面的答案会有所帮助
  • 好的,谢谢,我稍后试试

标签: python sql python-3.x sqlite


【解决方案1】:

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 是一个 dbfiddle。

要获得最重要的词,您可以使用:

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

【讨论】:

    【解决方案2】:

    你可以试试这个。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 2010-09-16
      相关资源
      最近更新 更多