2013-02-27 58 views
3

我有两个表。用SQL查询计数字出现

表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 
+1

对于有趣的问题+1。 – bonCodigo 2013-02-27 11:00:45

+0

http://whathaveyoutried.com。特别是如果这是一个家庭作业问题。 – 2013-02-27 11:03:36

+0

'table1'与'table2'有什么关系?第二只是第一个的另一种表现形式? – 2013-02-27 11:05:56

回答

2

您可以使用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

+0

谢谢!我会试着解决这个问题) – minerals 2013-02-27 11:36:06

0
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工程,以及正在核实

+1

我在你的查询中看不到'table1' – 2013-02-27 11:03:33

+0

@HamletHakobyan我会立即更新 – James 2013-02-27 11:05:20

+0

@HamletHakobyan检查一下现在是否有效 – James 2013-02-27 11:07:13

2

SQL DEMO

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 | 
0

有许多加盟的例子,所以,我将只添加字数例子:

Select REGEXP_COUNT('The shoes are good shoes.', ' ')+1 words_count 
From dual 
/

WORDS_COUNT 
----------- 
5 

SELECT id 
    , LISTAGG(word, ' ') WITHIN GROUP (ORDER BY id, word) AS words 
    , count(*) word_cnt 
    FROM your_table2 
GROUP BY id 
/

ID WORDS     WORD_CNT 
--------------------------------------- 
1 The are good shoes shoes 5 
2 There a is tree    4 
3 This is nice nice nice  5