How to count instances of character in SQL Column

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

    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!

提交回复
热议问题