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

前端 未结 4 1454
独厮守ぢ
独厮守ぢ 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:22

    If your requirement is to remove multiple spaces too, try this:

    Select length('500  text Oracle Parkway Redwood Shores CA') - length(REGEXP_REPLACE('500  text Oracle Parkway Redwood Shores CA',
    '( ){1,}', ''))  NumbofWords
    from dual;
    

    Since I have used the dual table you can test this directly in your own development environment.

    0 讨论(0)
  • 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 |
    
    0 讨论(0)
  • 2020-12-11 17:34

    Since you're using Oracle 11g it's even simpler-

    select regexp_count(your_column, '[^ ]+') from your_table
    

    Here is a sqlfiddle demo

    0 讨论(0)
  • 2020-12-11 17:40
    DECLARE @List       NVARCHAR(MAX) = '   ab a 
    x'; /*Your column/Param*/
    DECLARE @Delimiter  NVARCHAR(255) = ' ';/*space*/
    DECLARE @WordsTable TABLE (Data VARCHAR(1000));
    
    /*convert by XML the string to table*/
    INSERT INTO @WordsTable(Data)
    SELECT Data = y.i.value('(./text())[1]', 'VARCHAR(1000)')
    FROM 
    ( 
    SELECT x = CONVERT(XML, '<i>' 
        + REPLACE(@List, @Delimiter, '</i><i>') 
        + '</i>').query('.')
    ) AS a CROSS APPLY x.nodes('i') AS y(i)
    
    
    
    /*Your total words*/
    select count(*) NumberOfWords
    from @WordsTable
    where Data is not null;
    
    /*words list*/
    select *
    from @WordsTable
    where Data is not null
    

    /from this Logic you can continue alon/

    0 讨论(0)
提交回复
热议问题