首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用SQL查询统计单词出现次数

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

Stack Overflow用户
提问于 2013-02-27 18:57:13
回答 4查看 4.5K关注 0票数 3

我有两张桌子。

Table1:

代码语言:javascript
复制
ID   SENTENCE
1    The shoes are good shoes.
2    There is a tree.
3    This is nice, nice, nice!

Table2:

代码语言:javascript
复制
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

我需要计算Table1中每个句子中每个单词的出现次数。如果某个单词出现多次(>1),则对其进行计数,否则跳过该单词。最后,生成的表格应该如下所示:

代码语言:javascript
复制
ID   SENTENCE                   CNT
1    The shoes are good shoes.  2
2    There is a tree.
3    This is nice, nice, nice!  3
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-02-27 19:09:49

您可以使用count() over()

代码语言:javascript
复制
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()

代码语言:javascript
复制
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

票数 3
EN

Stack Overflow用户

发布于 2013-02-27 19:19:31

SQL DEMO

代码语言:javascript
复制
select t1.id, t1.sentence, 
coalesce(t2.cnt,0) as counts
from table1 t1
left join
(select id, word, count(id) cnt
from table2
group by id, word
having count(id) > 1)t2
on t1.id = t2.id
order by t1.id
;

| ID |                  SENTENCE | COUNTS |
-------------------------------------------
|  1 | The shoes are good shoes. |      2 |
|  2 |          There is a tree. |      0 |
|  3 | This is nice, nice, nice! |      3 |
票数 2
EN

Stack Overflow用户

发布于 2013-02-27 19:02:33

代码语言:javascript
复制
SELECT table1.id, table1.sentence, COUNT(word) as cnt FROM table2 JOIN table1 ON table1.id = table2.id GROUP BY table2.word HAVING COUNT(word) > 1

我的答案是mysql,我现在正在验证它在sql中也可以工作

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15110313

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档