如何计算Oracle中字符串中的单词数?

Dhe*_*jid 8 sql oracle oracle11g

我正在尝试计算SQL中字符串中有多少单词.

Select  ("Hello To Oracle") from dual;
Run Code Online (Sandbox Code Playgroud)

我想显示单词的数量.在给定的示例中,尽管单词之间可能存在多个空格,但它将是3个单词.

Tar*_*ryn 12

你可以使用类似的东西.这将获取字符串的长度,然后在删除空格的情况下减去字符串的长度.然后添加第一个应该给你的字数:

Select length(yourCol) - length(replace(yourcol, ' ', '')) + 1 NumbofWords
from yourtable
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo

如果您使用以下数据:

CREATE TABLE yourtable
    (yourCol varchar2(15))
;

INSERT ALL 
    INTO yourtable (yourCol)
         VALUES ('Hello To Oracle')
    INTO yourtable (yourCol)
         VALUES ('oneword')
    INTO yourtable (yourCol)
         VALUES ('two words')
SELECT * FROM dual
;
Run Code Online (Sandbox Code Playgroud)

和查询:

Select yourcol,
  length(yourCol) - length(replace(yourcol, ' ', '')) + 1 NumbofWords
from yourtable
Run Code Online (Sandbox Code Playgroud)

结果是:

|         YOURCOL | NUMBOFWORDS |
---------------------------------
| Hello To Oracle |           3 |
|         oneword |           1 |
|       two words |           2 |
Run Code Online (Sandbox Code Playgroud)


A.B*_*ade 6

由于您使用的是Oracle 11g,因此它更简单 -

select regexp_count(your_column, '[^ ]+') from your_table
Run Code Online (Sandbox Code Playgroud)

这是一个sqlfiddle演示