2016-07-28 62 views
0

假設字符串爲「這是字符串」發現在SQL Server中的字符串中的字符的出現次數

我必須定義一個表值函數輸出結果:

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

應該如何我這樣做?

+2

請發表您嘗試 –

回答

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 
+0

不錯!能否請你解釋一下,這將有所幫助......在返回語句 – BlackCat

+1

後,我不熟悉'WITH'等語法'WITH'語句是[公用表表達式](https://technet.microsoft.com/ en-us/library/ms190766(v = sql.105).aspx)(CTE)。此查詢使用[遞歸CTE](https://technet.microsoft.com/en-us/library/ms186243(v = sql.105).aspx)。 – Mono

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 
+0

感謝。但是,我很難理解它,因爲我是SQL Server的新手 – BlackCat

+0

@Zahid只是關閉了一天。在我的手機上。在AM中我會提供一個敘述。 –

+0

哦,那會很好,樂於助人 – BlackCat

相關問題