计算 SQL 中文本列中一组单词的出现次数

ACC*_*CCC 5 sql snowflake-cloud-data-platform

我有两个表如下:

CREATE TABLE keyword_tbl
(
    WORDS VARCHAR(100), 
    TOPIC VARCHAR(100)
); 

INSERT INTO keyword_tbl 
VALUES ('leaf', 'nature'), ('leaves', 'nature'),
       ('wind', 'nature'), ('knife', 'utensils'),
       ('knives', 'utensils'), ('calf', 'animal'),
       ('calves', 'animal')

CREATE TABLE content
(
    CONTENT_ID VARCHAR(100), 
    DESCRIPTION VARCHAR(100)
); 

INSERT INTO content 
VALUES ('uuid1', 'leaves fall in autumn like leafs'),
       ('uuid2', 'the calf is playing in the leaf, the knife' ),
       ('uuid3', 'knives cutting the wind'),
       ('uuid4', 'he says hi'),  
       ('uuid5', 'the calves running through the wind')
Run Code Online (Sandbox Code Playgroud)

我希望能够计算每个主题中每个单词的出现次数。我的理想输出如下所示。

内容ID 描述 自然 器皿 动物
uuid1 秋天的叶子像树叶一样落下 2 0 0
uuid2 小牛在树叶里玩耍,刀子 1 1 1
uuid3 刀斩风 1 1 0
uuid4 他打招呼 0 0 0
uuid5 乘风奔跑的小牛 1 0 1

解释 :

  • 对于 uuid1,我们进行计数leavesleaf因此 nature 的值为 2,
  • 对于 uuid2,我们计数calf, leafknife因此自然、器皿和动物的计数为 1,等等...

有没有办法可以自主完成此操作?

Luk*_*zda 3

使用STRTOK_SPLIT_TO_TABLE

使用给定的一组分隔符对字符串进行标记,并将结果展平为行。

SELECT c.CONTENT_ID, c.DESCRIPTION
      ,COUNT_IF(k.TOPIC = 'nature') AS nature
      ,COUNT_IF(k.TOPIC = 'utensils') AS utensils
      ,COUNT_IF(k.TOPIC = 'animal') AS animals
FROM content c
,LATERAL STRTOK_SPLIT_TO_TABLE(c.description, '(),. ') s
JOIN keyword_tbl k
  ON TRIM(s.value) = k.words
GROUP BY c.CONTENT_ID, c.DESCRIPTION
ORDER BY c.CONTENT_ID;
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述

要处理“leaf”,“leafs”需要更改连接条件:

 -- substring
 ON  TRIM(s.value) ILIKE  k.words|| '%'

 -- only 's'
 ON  TRIM(s.value) ILIKE ANY (k.words, k.words|| 's')
Run Code Online (Sandbox Code Playgroud)

输出:

在此输入图像描述