选择子列中用空格分隔的列中具有最高计数的子字符串

时间:2017-10-22 00:19:25

标签: sqlite select count

如何选择列中最常用的单词,其中单词用空格分隔?我正在使用SQLite作为数据库。

例如,

Column1  Column2
1        Apple Orange Banana
2        Strawberry Apple Pineapple
3        Grape Mango

所需输出:Apple

1 个答案:

答案 0 :(得分:0)

字数统计。假设您的表名为yourTable。使用公用表表达式(with子句)将Column2拆分为单独的单词。我从user1461607借用了一些知识并提出了这个:

WITH RECURSIVE split(word, str, hasspace) AS (
SELECT '', Column2, 1 from yourTable 
UNION ALL SELECT
substr(str, 0, 
    case when instr(str, ' ')
    then instr(str, ' ')
    else length(str)+1 end),
ltrim(substr(str, instr(str, ' ')), ' '),
instr(str, ' ')
FROM split
WHERE hasspace
)
SELECT trim(word) FROM split WHERE word!='' GROUP BY trim(word) ORDER BY count(*) DESC LIMIT 1