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

702 Views Asked by At

I have a database table with the following fields :

          ---------------------  
FIELDS :  | H1 | H2 | H3 | H4  
          ---------------------  
VALUES :  | A  | B  | A  | C   
          ---------------------  

For a given record (row), I would like to count the number of fields with a value of A. In the above, for example, there are two fields with a value of A, so the expected result would be : 2

How can I achieve this?

2

There are 2 best solutions below

0
Oliver Jakoubek On BEST ANSWER

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.

0
Samona On

I test this it work Thanx for help.

 SELECT count(H1) + count(H2) + count(H3) + count(H4) + count(H5) + 
count(H6) + count(H7) + count(H8) as TOT
from Table T
where T.H1 = 'A' or T.H2 = 'A' or T.H3 = 'A' or T.H4 = 'A' 
or T.H5 = 'A' or T.H6 = 'A' or T.H7 = 'A' or T.H8 = 'A'
group by T.ID
order by 1 DESC 

Other solution ...