How can I count the number of words in a string in Oracle?

前端 未结 4 1471
独厮守ぢ
独厮守ぢ 2020-12-11 16:49

I\'m trying to count how many words there are in a string in SQL.

Select  (\"Hello To Oracle\") from dual;

I want to show the number of wor

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-11 17:27

    You can use something similar to this. This gets the length of the string, then substracts the length of the string with the spaces removed. By then adding the number one to that should give you the number of words:

    Select length(yourCol) - length(replace(yourcol, ' ', '')) + 1 NumbofWords
    from yourtable
    

    See SQL Fiddle with Demo

    If you use the following data:

    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
    ;
    

    And the query:

    Select yourcol,
      length(yourCol) - length(replace(yourcol, ' ', '')) + 1 NumbofWords
    from yourtable
    

    The result is:

    |         YOURCOL | NUMBOFWORDS |
    ---------------------------------
    | Hello To Oracle |           3 |
    |         oneword |           1 |
    |       two words |           2 |
    

提交回复
热议问题