如何知道给出char的出现次数和出现的次数

时间:2017-12-21 05:53:36

标签: sql sql-server stored-procedures

我正在使用SQL Server 2008,我遇到以下问题。

我有一张这样的表:

enter image description here

每列代表一年,目的是知道在任何列中是否有重复的字符定义的次数(要查找的字符和出现的次数是参数)。

问题是,我怎么知道是否有一个列出现n次出现的字符参数?

例如,只知道在某些记录中,在任何列中是否有字符' 2'重复3次

您执行的示例:我搜索字符' 1'在ANIO_1栏中重复6次

{{1}}

但问题的目的是如何知道数字1是否在表格的任何一列中重复6次

感谢您的帮助,对不起我的英语

1 个答案:

答案 0 :(得分:0)

我创建了一个样本。请参阅http://sqlfiddle.com/#!6/67d2a/1

DECLARE @OccuranceChars INT
DECLARE @FindSubString VARCHAR(5)
SET @FindSubString = '2'
SET @OccuranceChars = 3

SELECT ANIO_1, 
(LEN(ANIO_1) - LEN(REPLACE(ANIO_1, @FindSubString, '')))/LEN(@FindSubString) as Occurance_ANIO_1, 
ANIO_2, 
(LEN(ANIO_2) - LEN(REPLACE(ANIO_2, @FindSubString, '')))/LEN(@FindSubString) as Occurance_ANIO_2,
ANIO_3, 
(LEN(ANIO_3) - LEN(REPLACE(ANIO_3, @FindSubString, '')))/LEN(@FindSubString) as Occurance_ANIO_3,
ANIO_4, 
(LEN(ANIO_4) - LEN(REPLACE(ANIO_4, @FindSubString, '')))/LEN(@FindSubString) as Occurance_ANIO_4,
ANIO_5, 
(LEN(ANIO_5) - LEN(REPLACE(ANIO_5, @FindSubString, '')))/LEN(@FindSubString) as Occurance_ANIO_5,
ANIO_6, 
(LEN(ANIO_6) - LEN(REPLACE(ANIO_6, @FindSubString, '')))/LEN(@FindSubString) as Occurance_ANIO_6
FROM ANIO
WHERE (LEN(ANIO_1) - LEN(REPLACE(ANIO_1, @FindSubString, '')))/LEN(@FindSubString) = @OccuranceChars
OR (LEN(ANIO_2) - LEN(REPLACE(ANIO_2, @FindSubString, '')))/LEN(@FindSubString) = @OccuranceChars
OR (LEN(ANIO_3) - LEN(REPLACE(ANIO_3, @FindSubString, '')))/LEN(@FindSubString) = @OccuranceChars
OR (LEN(ANIO_4) - LEN(REPLACE(ANIO_4, @FindSubString, '')))/LEN(@FindSubString) = @OccuranceChars
OR (LEN(ANIO_5) - LEN(REPLACE(ANIO_5, @FindSubString, '')))/LEN(@FindSubString) = @OccuranceChars
OR (LEN(ANIO_6) - LEN(REPLACE(ANIO_6, @FindSubString, '')))/LEN(@FindSubString) = @OccuranceChars

以上查询将检查" 2"数字在#34; ANIO_1"列中存在完全 3次。对于所有列,您可以重复相同的事情,

否则创建UDF - 用户定义的函数,该函数接受参数@FindSubString&列值