Programming

SQL 열에서 문자 인스턴스를 계산하는 방법

procodes 2020. 8. 19. 20:19
반응형

SQL 열에서 문자 인스턴스를 계산하는 방법


100 개의 'Y'또는 'N'자 문자열 인 SQL 열이 있습니다. 예를 들면 :

YYNYNYYNNNYYNY ...

각 행의 모든 ​​'Y'기호 수를 얻는 가장 쉬운 방법은 무엇입니까?


SQL Server에서 :

SELECT LEN(REPLACE(myColumn, 'N', '')) 
FROM ...

이 스 니펫은 부울이있는 특정 상황에서 작동합니다. "비 N이 몇 개입니까?"라고 대답합니다.

SELECT LEN(REPLACE(col, 'N', ''))

다른 상황에서 실제로 주어진 문자열에서 특정 문자 (예 : 'Y')의 발생 횟수를 계산하려는 경우 다음을 사용하십시오.

SELECT LEN(col) - LEN(REPLACE(col, 'Y', ''))

이것은 매번 정확한 결과를주었습니다 ...

이것은 내 줄무늬 필드에 있습니다 ...

노란색, 노란색, 노란색, 노란색, 노란색, 노란색, 검은 색, 노란색, 노란색, 빨간색, 노란색, 노란색, 노란색, 검은 색

  • 11 노란색
  • 2 검정
  • 1 빨간색
SELECT (LEN(Stripes) - LEN(REPLACE(Stripes, 'Red', ''))) / LEN('Red') 
  FROM t_Contacts

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]

아마 이런거 ...

SELECT
    LEN(REPLACE(ColumnName, 'N', '')) as NumberOfYs
FROM
    SomeTable

가장 쉬운 방법은 Oracle 기능을 사용하는 것입니다.

SELECT REGEXP_COUNT(COLUMN_NAME,'CONDITION') FROM TABLE_NAME

이 시도

declare @v varchar(250) = 'test.a,1  ;hheuw-20;'
-- LF   ;
select len(replace(@v,';','11'))-len(@v)

이 시도. 아니오를 결정합니다. 단일 문자 발생 및 기본 문자열의 하위 문자열 발생.

SELECT COUNT(DECODE(SUBSTR(UPPER(:main_string),rownum,LENGTH(:search_char)),UPPER(:search_char),1)) search_char_count
FROM DUAL
connect by rownum <= length(:main_string);

두 개 이상의 문자가있는 문자열의 인스턴스 수를 계산하려면 정규식과 함께 이전 솔루션을 사용하거나이 솔루션이 SQL Server 2016에 도입 된 것으로 생각되는 STRING_SPLIT를 사용합니다. 또한 호환성이 필요합니다. 레벨 130 이상.

ALTER DATABASE [database_name] SET COMPATIBILITY_LEVEL = 130

.

--some data
DECLARE @table TABLE (col varchar(500))
INSERT INTO @table SELECT 'whaCHAR(10)teverCHAR(10)whateverCHAR(10)'
INSERT INTO @table SELECT 'whaCHAR(10)teverwhateverCHAR(10)'
INSERT INTO @table SELECT 'whaCHAR(10)teverCHAR(10)whateverCHAR(10)~'

--string to find
DECLARE @string varchar(100) = 'CHAR(10)'

--select
SELECT 
    col
  , (SELECT COUNT(*) - 1 FROM STRING_SPLIT (REPLACE(REPLACE(col, '~', ''), 'CHAR(10)', '~'), '~')) AS 'NumberOfBreaks'
FROM @table

nickf가 제공하는 두 번째 답변은 매우 영리합니다. 그러나 대상 하위 문자열 1의 문자 길이에 대해서만 작동하고 공백을 무시합니다. 특히 내 데이터에는 두 개의 선행 공백이 있었는데, 오른쪽의 모든 문자가 제거되면 SQL이 유용하게 제거합니다 (이는 몰랐습니다). 그 의미

" 존 스미스"

Nickf의 방법을 사용하여 12를 생성 한 반면 :

"Joe Bloggs, John Smith"

generated 10, and

" Joe Bloggs, John Smith, John Smith"

Generated 20.

I've therefore modified the solution slightly to the following, which works for me:

Select (len(replace(Sales_Reps,' ',''))- len(replace((replace(Sales_Reps, ' ','')),'JohnSmith','')))/9 as Count_JS

I'm sure someone can think of a better way of doing it!


You can also Try This

-- DECLARE field because your table type may be text
DECLARE @mmRxClaim nvarchar(MAX) 

-- Getting Value from table
SELECT top (1) @mmRxClaim = mRxClaim FROM RxClaim WHERE rxclaimid_PK =362

-- Main String Value
SELECT @mmRxClaim AS MainStringValue

-- Count Multiple Character for this number of space will be number of character
SELECT LEN(@mmRxClaim) - LEN(REPLACE(@mmRxClaim, 'GS', ' ')) AS CountMultipleCharacter

-- Count Single Character for this number of space will be one
SELECT LEN(@mmRxClaim) - LEN(REPLACE(@mmRxClaim, 'G', '')) AS CountSingleCharacter

Output:

enter image description here


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 --Correct

SELECT LEN(REPLACE('123a123a12', 'a', ''));
--8 --Wrong

SELECT LEN(REPLACE('123a123a12', '1', ''));
--7 --Wrong

2) Try with below solution for correct output:

  • Create a function and also modify as per requirement.
  • And call function as per below

select dbo.vj_count_char_from_string('123a123a12','2');
--2 --Correct

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

This will return number of occurance of N

select ColumnName, LEN(ColumnName)- LEN(REPLACE(ColumnName, 'N', '')) from Table


Here's what I used in Oracle SQL to see if someone was passing a correctly formatted phone number:

WHERE REPLACE(TRANSLATE('555-555-1212','0123456789-','00000000000'),'0','') IS NULL AND
LENGTH(REPLACE(TRANSLATE('555-555-1212','0123456789','0000000000'),'0','')) = 2

The first part checks to see if the phone number has only numbers and the hyphen and the second part checks to see that the phone number has only two hyphens.


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

참고URL : https://stackoverflow.com/questions/1860457/how-to-count-instances-of-character-in-sql-column

반응형