SQL计算多列中的某些值

时间:2015-01-31 06:22:29

标签: php mysql sql

我有一个包含3个可能值(1,0,NA)的表

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

我试图只计算1和0作为值。

我想要实现的查询结果是:

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

将MySQL用于数据库。

我尝试过使用: SELECT Customers, COUNT(Answer1 + Answer2 + Answer3) AS Total_Score FROM exam。 SQL查询只对值进行求和,而不是计算值1和0.感谢您的所有帮助。我一直被困住并一直在寻找,但没有运气。

2 个答案:

答案 0 :(得分:3)

如果您有同一客户的多条记录,请执行

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

或者每个客户只有一个

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

SQLFiddle demo

答案 1 :(得分:0)

有几种查询模式将返回指定的结果。我的偏好是明确检查列是否包含01,如果有,则返回1,否则返回0,然后将它们一起添加。

例如,使用MySQL IF() 功能:

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

ANSI等效项将使用CASE表达式代替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