tags:

views:

162

answers:

3

I have an sql column that is a string of 100 Y or Ns eg 'YYNYNYYNNNYYNY...' What is the easiest way to get the number of Ys in each row.

+5  A: 

if ms sql

SELECT LEN(REPLACE(myColumn, 'N', '')) FROM ...
David Hedlund
Very clever solution!
cindi
thanks =) please tick the answer as accepted if you're happy with it
David Hedlund
Just be aware that if there are more than "N" or "Y" in the string then this could be inaccurate. See nickf's solution for a more robust method.
Tom H.
+1  A: 

Maybe something like this...

SELECT
    LEN(REPLACE(ColumnName, 'N', '')) as NumberOfYs
FROM
    SomeTable
Jason Punyon
+8  A: 

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

SELECT LENGTH(REPLACE(`col`, 'N', ''))

If, in a different situation, you were actually trying to count the occurrences of a certain character in any given string, use this:

SELECT LENGTH(col) - LENGTH(REPLACE(col, 'Y', ''))
nickf