如何对所有计数(案例)子列求和?

时间:2019-03-28 07:56:17

标签: mysql sql select phpmyadmin xampp

我正在创建一个表,该表可以对三列中的所有“异常”数据进行计数并将这些列求和。

SELECT

  COUNT(CASE WHEN p_eyes <> 'Normal' THEN 1 END) AS 'abnormalEyes',
  COUNT(CASE WHEN p_ears <> 'Normal' THEN 1 END) AS 'abnormalEars',
  COUNT(CASE WHEN p_nose <> 'Normal' THEN 1 END) AS 'abnormalNose'

FROM student_physical_record_exam_grade_eleven;

这将计算这三列中所有非“正常”的数字。

有什么办法可以将这三列总计为“眼睛/耳朵/鼻子”?

1 个答案:

答案 0 :(得分:1)

如果只想对这些结果求和,可以将它们相加。最简单的方法是使用子查询:

SELECT *, abnormalEyes + abnormalEars + abnormalNose AS totalAbnormal
FROM   (SELECT COUNT(CASE WHEN p_eyes <> 'Normal' THEN 1 END) AS abnormalEyes,
               COUNT(CASE WHEN p_ears <> 'Normal' THEN 1 END) AS abnormalEars,
               COUNT(CASE WHEN p_nose <> 'Normal' THEN 1 END) AS abnormalNose
FROM   student_physical_record_exam_grade_eleven) t