我有一个带有几个列的注册表,其中包含“正在进行”或“已提交”等值。我试图计算这些列中有多少列等于“提交”,这样我就可以确定用户的完成百分比。下面的查询显然只返回0或1,因为它只查询一个列,但如何合并其他列?
例如,我想计算下列列中有多少列等于“已提交”或“已接受”:
network_user_status
work_ed_status
chores_status
class_schedule_status
SELECT COUNT(id) FROM registration WHERE username = "ajackson" AND enrollment_agreement_status = "accepted" OR enrollment_agreement_status = "submitted"
最佳答案
首先,你的查询没有做你认为它在做的事情。username
条件仅适用于“已接受”。我很确定你的意思是:
SELECT COUNT(id)
FROM registration
WHERE username = 'ajackson' AND enrollment_agreement_status in ('accepted', 'submitted')
如果要计算一个或另一个或两个值,请使用条件聚合。这在mysql中很简单:
select count(id), sum(enrollment_agreement_status = 'accepted') as accepted,
sum(enrollment_agreement_status = 'submitted') as submitted
from registration
where username = 'ajackson';