[英]SQL count certain values in multiple columns
I have a table with with 3 possible values (1,0,NA) 我有一个带有3个可能值(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. 我试图仅将1和0作为值。
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. 对数据库使用MySQL。
I tried using: SELECT Customers, COUNT(Answer1 + Answer2 + Answer3) AS Total_Score FROM exam
. 我尝试使用:
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. SQL查询仅对值求和,而不对值1和0进行计数。感谢您的所有帮助。 I have been stuck and been searching, but no luck.
我一直被困住并一直在寻找,但没有运气。
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
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. 我的偏好是显式检查该列是否包含
0
或1
,如果包含则返回1
,否则返回0,然后将它们加在一起。
For example, using the MySQL IF()
function: 例如,使用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
The ANSI equivalent would use CASE
expressions in place of the IF()
: 相当于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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.