简体   繁体   中英

Count all occurrences of text in a column

I want to count all occurrences of a particular word in a varchar(200) column.

My data is something like this:

ID    MyText
---   --------------------------------------
1     Hello how are you doing? Hello again.
2     This is great.
3     Hello my special person.

So I want SQL to do a like '%Hello%' and come back with the number 3. I don't care right now is for instance partial words are included and don't care right now on the like with wildcards. I only need this for some simple testing to validate some things.

WITH T(ID,MyText) AS
(
SELECT 1, 'Hello how are you doing? Hello again.' UNION ALL
SELECT 2, 'This is great.' UNION ALL
SELECT 3, 'Hello my special person.'
)
SELECT *, 
       (LEN(MyText) - LEN(REPLACE(MyText, 'Hello', ''))) / LEN('Hello') AS Num
FROM T

Or

SELECT  SUM((LEN(MyText) - LEN(REPLACE(MyText, 'Hello', ''))) / LEN('Hello'))
FROM T

for an aggregate result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM