I have an sql column that is a string of 100 \'Y\' or \'N\' characters. For example:
YYNYNYYNNNYYNY...
What is the easiest way
This will return number of occurance of N
select ColumnName, LEN(ColumnName)- LEN(REPLACE(ColumnName, 'N', ''))
from Table
for example to calculate the count instances of character (a) in SQL Column ->name is column name '' ( and in doblequote's is empty i am replace a with nocharecter @'')
select len(name)- len(replace(name,'a','')) from TESTING
select len('YYNYNYYNNNYYNY')- len(replace('YYNYNYYNNNYYNY','y',''))
This gave me accurate results every time...
This is in my Stripes field...
Yellow, Yellow, Yellow, Yellow, Yellow, Yellow, Black, Yellow, Yellow, Red, Yellow, Yellow, Yellow, Black
SELECT (LEN(Stripes) - LEN(REPLACE(Stripes, 'Red', ''))) / LEN('Red')
FROM t_Contacts
Below solution help to find out no of character present from a string with a limitation:
1) using SELECT LEN(REPLACE(myColumn, 'N', '')), but limitation and wrong output in below condition:
SELECT LEN(REPLACE('YYNYNYYNNNYYNY', 'N', ''));
--8 --CorrectSELECT LEN(REPLACE('123a123a12', 'a', ''));
--8 --WrongSELECT LEN(REPLACE('123a123a12', '1', ''));
--7 --Wrong
2) Try with below solution for correct output:
select dbo.vj_count_char_from_string('123a123a12','2');
--2 --Correctselect dbo.vj_count_char_from_string('123a123a12','a');
--2 --Correct
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: VIKRAM JAIN
-- Create date: 20 MARCH 2019
-- Description: Count char from string
-- =============================================
create FUNCTION vj_count_char_from_string
(
@string nvarchar(500),
@find_char char(1)
)
RETURNS integer
AS
BEGIN
-- Declare the return variable here
DECLARE @total_char int; DECLARE @position INT;
SET @total_char=0; set @position = 1;
-- Add the T-SQL statements to compute the return value here
if LEN(@string)>0
BEGIN
WHILE @position <= LEN(@string) -1
BEGIN
if SUBSTRING(@string, @position, 1) = @find_char
BEGIN
SET @total_char+= 1;
END
SET @position+= 1;
END
END;
-- Return the result of the function
RETURN @total_char;
END
GO
If you need to count the char in a string with more then 2 kinds of chars, you can use instead of 'n' -
some operator or regex of the chars accept the char you need.
SELECT LEN(REPLACE(col, 'N', ''))
DECLARE @StringToFind VARCHAR(100) = "Text To Count"
SELECT (LEN([Field To Search]) - LEN(REPLACE([Field To Search],@StringToFind,'')))/COALESCE(NULLIF(LEN(@StringToFind), 0), 1) --protect division from zero
FROM [Table To Search]