How to count instances of character in SQL Column

前端 未结 16 1634
你的背包
你的背包 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:37

    Maybe something like this...

    SELECT
        LEN(REPLACE(ColumnName, 'N', '')) as NumberOfYs
    FROM
        SomeTable
    
    0 讨论(0)
  • 2020-11-27 13:37

    The easiest way is by using Oracle function:

    SELECT REGEXP_COUNT(COLUMN_NAME,'CONDITION') FROM TABLE_NAME
    
    0 讨论(0)
  • 2020-11-27 13:37

    If you want to count the number of instances of strings with more than a single character, you can either use the previous solution with regex, or this solution uses STRING_SPLIT, which I believe was introduced in SQL Server 2016. Also you’ll need compatibility level 130 and higher.

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

    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.

    0 讨论(0)
提交回复
热议问题