How can I count the number of times that a particular character occurs in a column in Oracle? For example, if I have a table FOO
that has data like a,ABC,def
and 2,3,4,5
, I want to count the number of times that a comma appears in the data.
CREATE TABLE foo (
str varchar2(30)
);
INSERT INTO foo VALUES( 'a,ABC,def' );
INSERT INTO foo VALUES( '2,3,4,5' );
commit;
The output that I want is
str cnt
a,ABC,def 2
2,3,4,5 3
The Oracle/PLSQL REGEXP_COUNT function counts the number of times that a pattern occurs in a string. This function, introduced in Oracle 11g, will allow you to count the number of times a substring occurs in a string using regular expression pattern matching.
To count how many occurrences of a character, say 'x' , exist in a string like 'zxxydds' , the fastest way is to use the string function REPLACE() to remove all the occurrences of 'x' from the string (by replacing 'x' with '' ), and then to subtract the length of the resulting string from the length of the original ...
T-SQL doesn't provide a built-in function to count the number of times a particular string appears within another string, so to find out how many times a word appears in a row, you have to build your own count function. SQL Server 2000 lets you create this kind of user-defined function (UDF).
One of the usual tricks for this is to use a combination of length
and replace
:
select (length(your_col) - length(replace(your_col, ','))) from your_table;
replace
without a third argument will simply remove the character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With