比较相同列MySQL的计数以获得百分比

时间:2018-04-30 18:50:18

标签: mysql count subquery percentage

我需要做的是:

获得该课程中所有课堂调查的百分比,其中问题1的答案大于3.

我有一张表格,其中包含一个庞大的课堂调查数据集。例如,GENE01可能会对5名不同的学生进行5次调查;所以我有4个班级,但有50个与他们相关的调查。

目前,我正在运行两个查询来完成此任务,但我希望它是一个单一的查询。以下是我想要结合的两个查询。

-- Query 1
SELECT COUNT(survey_ID) as total 
FROM survey_Table
WHERE courseName LIKE 'GENE01'
   OR courseName LIKE 'GENE02'
   OR courseName LIKE 'GENE03'
   OR courseName LIKE 'GENE04'
GROUP BY survey_ID WITH ROLLUP
; 
-- Query 2
SELECT COUNT (survey_ID) as newTotal
FORM survey_Table
WHERE courseName LIKE 'GENE01' AND question1 > 3
   OR courseName LIKE 'GENE02' AND question1 > 3
   OR courseName LIKE 'GENE03' AND question1 > 3
   OR courseName LIKE 'GENE04' AND question1 > 3
GROUP BY survey_ID WITH ROLLUP
; 

然后我从我的桌面手动拿一个计算器并执行newTotal / total * 100.我无法弄清楚子查询(或者你需要做什么)来完成这个简单的任务。我想我遇到的问题是我不知道如何比较同一列的计数。

谢谢大家,对不起,我对MySQL很陌生。

2 个答案:

答案 0 :(得分:1)

条件聚合是一种可能的方法:

 SELECT s.survey_ID
      , SUM(1)                AS total
      , SUM(s.question1 > 3)  AS newTotal
   FROM survey_Table s
  WHERE s.courseName IN ('GENE01','GENE02','GENE03','GENE04')
  GROUP
     BY s.survey_ID
   WITH ROLLUP

注意条件s.question1 > 3是MySQL的简写。 MySQL对其进行求值并返回1表示TRUE,返回0表示FALSE,如果为空则返回NULL。

这几乎相当于更符合标准的ANSI标准:

 SUM(CASE WHEN s.question1 > 3 THEN 1 ELSE 0 END)   AS newTotal

处理NULL值的区别在于。

更精确地重写SUM(s.question1 > 3)将是

 SUM(CASE WHEN s.question1 > 3 THEN 1 WHEN s.question1 IS NULL THEN NULL ELSE 0 END)

对于返回的每一行,将评估SUM()聚合内的表达式。 1始终评估为1

可以从SELECT列表中省略survey_ID。通常,当我们执行GROUP BY foo时,我们对哪个结果行与foo相关联感兴趣。

这个问题要求获得"百分比"。我们可以在SELECT列表中的表达式中进行除法。但我不认为" with rollup"会让你得到你所期待的东西。

以下是一个例子:

 SELECT SUM(1)                AS total
      , SUM(s.question1 > 3)  AS newTotal

      , 100.0
      * SUM(s.question1 > 3) 
      / SUM(1)                 AS percentage

   FROM survey_Table s
  WHERE s.courseName IN ('GENE01','GENE02','GENE03','GENE04')

在此示例中,我选择省略GROUP BY子句。所以这将返回一个总的总行数,这将得到我们一个整体百分比。 (如果我们使用GROUP BYWITH ROLLUP,则会增加百分比。而且可能不是我们之后的结果。)

答案 1 :(得分:0)

您可以通过survey_id

加入查询
    select t1.survey_ID, t2.newTotal/t1.total 
    from (
    SELECT survey_ID, COUNT (survey_ID) as newTotal
    FORM survey_Table
    WHERE courseName LIKE 'GENE01' AND question1 > 3
       OR courseName LIKE 'GENE02' AND question1 > 3
       OR courseName LIKE 'GENE03' AND question1 > 3
       OR courseName LIKE 'GENE04' AND question1 > 3
    GROUP BY survey_ID ) 
    INNER JOIN (

    SELECT survey_ID, COUNT(survey_ID) as total 
    FROM survey_Table
    WHERE courseName LIKE 'GENE01'
       OR courseName LIKE 'GENE02'
       OR courseName LIKE 'GENE03'
       OR courseName LIKE 'GENE04'
    GROUP BY survey_ID ) t2. ON t1.survey_ID = t2.survey_ID