Counting the number of occurrences of a substring within a string in PostgreSQL

后端 未结 5 994
南旧
南旧 2020-12-03 09:49

How can I count the number of occurrences of a substring within a string in PostgreSQL?


Example:

I have a table

CREATE TABLE test.\"use         


        
5条回答
  •  我在风中等你
    2020-12-03 10:12

    A common solution is based on this logic: replace the search string with an empty string and divide the difference between old and new length by the length of the search string

    (CHAR_LENGTH(name) - CHAR_LENGTH(REPLACE(name, 'substring', ''))) 
    / CHAR_LENGTH('substring')
    

    Hence:

    UPDATE test."user"
    SET result = 
        (CHAR_LENGTH(name) - CHAR_LENGTH(REPLACE(name, 'o', ''))) 
        / CHAR_LENGTH('o');
    

提交回复
热议问题