Rob Sands
Rob Sands

Reputation: 65

SQL count certain values in multiple columns

I have a table with with 3 possible values (1,0,NA)

Customers | Answer1 | Answer2 | Answer3
-----------------------------------
John      |   1     |  0     |  NA 
Dave      |   NA    |  0     |  NA      
Jane      |   0     |  1     |  1
Tom       |   1     |  0     |  0

I am trying to count only the 1 and 0 as values.

The result of query that I am trying to achieve is:

Customers | Total_Score
-----------------------
John      |    2
Dave      |    1
Jane      |    3
Tom       |    3

Using MySQL for a database.

I tried using: SELECT Customers, COUNT(Answer1 + Answer2 + Answer3) AS Total_Score FROM exam. The SQL query only summed the values, not count the values 1 and 0. Thanks for all your help. I have been stuck and been searching, but no luck.

Upvotes: 0

Views: 84

Answers (2)

juergen d
juergen d

Reputation: 204746

If you have multiple records of the same customer then do

SELECT Customers,
       sum((Answer1 <> 'NA') + (Answer2 <> 'NA') + (Answer3 <> 'NA')) AS Total_Score 
FROM exam
group by Customers

or if only one per customer then

SELECT Customers,
       (Answer1 <> 'NA') + (Answer2 <> 'NA') + (Answer3 <> 'NA') AS Total_Score 
FROM exam

SQLFiddle demo

Upvotes: 3

spencer7593
spencer7593

Reputation: 108370

There are several query patterns that will return the specified result. My preference would be to explicitly check that the column contains a 0 or 1, and return 1 if it does, and zero otherwise, and then add those together.

For example, using the MySQL IF() function:

SELECT e.Customers
     , IF(e.Answer1 IN ('0','1'), 1, 0) 
     + IF(e.Answer2 IN ('0','1'), 1, 0) 
     + IF(e.Answer3 IN ('0','1'), 1, 0)
       AS Total_Score   
 FROM exam e

The ANSI equivalent would use CASE expressions in place of the IF():

SELECT e.Customers
     , CASE WHEN e.Answer1 IN ('0','1') THEN 1 ELSE 0 END
     + CASE WHEN e.Answer2 IN ('0','1') THEN 1 ELSE 0 END
     + CASE WHEN e.Answer3 IN ('0','1') THEN 1 ELSE 0 END
       AS Total_Score   
 FROM exam e

Upvotes: 0

Related Questions