[Solved] How to return a count of fields with a given value in a record?


I am trying to answer the question from a database point of view.

You have a table with one or more rows and every row has in the four columns either an ‘A’ or something else. For a given row (or for many rows) you want to get the number of columns that have an ‘A’ in it.

As one commenter pointed out you can’t sum letters but you can check whether or not a value is the one you are looking for and then count this occurence as a 1 or 0. Finally sum those values and return the sum.

SELECT (CASE H1 WHEN 'A' THEN 1 ELSE 0 END) +
       (CASE H2 WHEN 'A' THEN 1 ELSE 0 END) +
       (CASE H3 WHEN 'A' THEN 1 ELSE 0 END) +
       (CASE H4 WHEN 'A' THEN 1 ELSE 0 END) AS number_of_a
FROM   name_of_your_table;

For your example row this will return:

NUMBER_OF_A
===========
          2

If you have more than one row you’ll get the number of As for every row.

solved How to return a count of fields with a given value in a record?