gpt4 book ai didi

sql - 使用 SQL 查询统计单词出现次数

转载 作者:行者123 更新时间:2023-12-03 03:00:26 25 4
gpt4 key购买 nike

我有两张 table 。

表1:

ID   SENTENCE
1 The shoes are good shoes.
2 There is a tree.
3 This is nice, nice, nice!

表2:

ID   WORD
1 The
1 shoes
1 are
1 good
1 shoes
2 There
2 is
2 a
2 tree
3 This
3 is
3 nice
3 nice
3 nice

我需要统计表1中每个句子中每个单词的出现次数。如果任何单词出现多次 (>1),则计算它,否则跳过它。最后生成的表格应如下所示:

ID   SENTENCE                   CNT
1 The shoes are good shoes. 2
2 There is a tree.
3 This is nice, nice, nice! 3

最佳答案

您可以使用count() over():

select distinct t1.id,
t1.sentence,
coalesce(t2.cnt, 0) cnt
from table1 t1
left join
(
select t1.id,
t1.sentence,
t2.word,
count(t2.word) over(partition by t1.id, t2.word) cnt
from table1 t1
left join table2 t2
on t1.id = t2.id
) t2
on t1.id = t2.id
and t2.cnt > 1
order by t1.id

参见SQL Fiddle with Demo .

或者您可以只使用count():

select t1.id,
t1.sentence,
coalesce(t2.cnt, 0) cnt
from table1 t1
left join
(
select t1.id,
t1.sentence,
t2.word,
count(t2.word) cnt
from table1 t1
left join table2 t2
on t1.id = t2.id
group by t1.id, t1.sentence, t2.word
having count(t2.word) > 1
) t2
on t1.id = t2.id
order by t1.id

参见SQL Fiddle with Demo

关于sql - 使用 SQL 查询统计单词出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15110313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com