How to count instances of character in SQL Column

前端 未结 16 1628
你的背包
你的背包 2020-11-27 12:57

I have an sql column that is a string of 100 \'Y\' or \'N\' characters. For example:

YYNYNYYNNNYYNY...

What is the easiest way

相关标签:
16条回答
  • 2020-11-27 13:24

    Try This. It determines the no. of single character occurrences as well as the sub-string occurrences in main string.

    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);
    
    0 讨论(0)
  • 2020-11-27 13:24

    The second answer provided by nickf is very clever. However, it only works for a character length of the target sub-string of 1 and ignores spaces. Specifically, there were two leading spaces in my data, which SQL helpfully removes (I didn't know this) when all the characters on the right-hand-side are removed. Which meant that

    " John Smith"

    generated 12 using Nickf's method, whereas:

    " 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!

    0 讨论(0)
  • 2020-11-27 13:27

    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:

    0 讨论(0)
  • 2020-11-27 13:28

    In SQL Server:

    SELECT LEN(REPLACE(myColumn, 'N', '')) 
    FROM ...
    
    0 讨论(0)
  • 2020-11-27 13:31

    This snippet works in the specific situation where you have a boolean: it answers "how many non-Ns are there?".

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

    If, in a different situation, you were actually trying to count the occurrences of a certain character (for example 'Y') in any given string, use this:

    SELECT LEN(col) - LEN(REPLACE(col, 'Y', ''))
    
    0 讨论(0)
  • 2020-11-27 13:34

    try this

    declare @v varchar(250) = 'test.a,1  ;hheuw-20;'
    -- LF   ;
    select len(replace(@v,';','11'))-len(@v)
    
    0 讨论(0)
提交回复
热议问题