简体   繁体   中英

Finding number of occurrence of characters in a string in SQL Server

Suppose the string is "this is string"

I have to define a table valued function to output the result:

+------+-------+
| char | count |
+------+-------+
|      |   3   |
| t    |   2   |
| h    |   1   |
| i    |   3   |
| s    |   3   |
| a    |   1   |
| r    |   1   |
| n    |   1   |
|  g   |   1   |
+------+-------+

How should I do this?

CREATE FUNCTION [dbo].[udfCharCount] (@String varchar(max))

Returns Table

As
Return

    Select Char,Count=count(*) 
     From (
            Select Char = Substring(a.b, v.number+1, 1) 
             From (select @String b) a
             Join master..spt_values v on v.number < len(a.b) where v.type = 'P'
          ) A
     Group By Char


-- Syntax Select * from [dbo].[udfCharCount]('this is a string') 

Returns

Char    Count
        3
a       1
g       1
h       1
i       3
n       1
r       1
s       3
t       2
CREATE FUNCTION CountCharacterOccurences(@str nvarchar(max))
RETURNS TABLE
AS
RETURN
    WITH Nums(n) -- Generate numbers from 1 to LEN(@str)
    AS(
        SELECT 1
        UNION ALL
        SELECT n+1
        FROM Nums
        WHERE n+1 <= LEN(@str)
    )
    SELECT 
        SUBSTRING(@str, n, 1) AS char, 
        COUNT(*) AS count
    FROM Nums
    GROUP BY SUBSTRING(@str, n, 1)

Usage

DECLARE @str VARCHAR(max)
SET @str = 'this is a string';

SELECT * FROM  CountCharacterOccurences(@str)

Returns

char count
    3
a   1
g   1
h   1
i   3
n   1
r   1
s   3
t   2

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