查找SQL Server中字符串中出现的字符数

时间:2016-07-28 03:56:22

标签: sql sql-server

假设字符串是"这是字符串"

我必须定义一个表值函数来输出结果:

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

我该怎么做?

2 个答案:

答案 0 :(得分:2)

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') 

返回

Char    Count
        3
a       1
g       1
h       1
i       3
n       1
r       1
s       3
t       2

答案 1 :(得分:1)

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)

用法

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

SELECT * FROM  CountCharacterOccurences(@str)

返回

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