WHERE条件别名不起作用

时间:2014-08-01 10:54:57

标签: mysql sql group-by where

我有这样的查询

SELECT 
table1.question_id,
SUM(IF(table1.correct_answer = 1, 1, 0)) AS correct_answers,
SUM(IF(table1.correct_answer != 1, 1, 0)) AS incorrect_answers,
round((SUM(IF(table1.correct_answer = 1, 1, 0)) / (SUM(IF(table1.correct_answer = 1, 1, 0)) + SUM(IF(table1.correct_answer != 1, 1, 0))) * 100),
        2) AS percentage
FROM
    table2
        JOIN
    table1 ON table2.answer_id = table1.id
WHERE
    percentage BETWEEN 10 AND 20
group by table1.question_id;

我正在尝试获取question_id,正确答案的数量,错误答案的数量以及正确的百分比,即某个值之间的百分比。现在一切都在工作以外的地方。它显示未知的列'百分比'。

2 个答案:

答案 0 :(得分:1)

不仅where子句中不允许列别名,而且您需要的逻辑需要having子句。这是在聚合的结果:

SELECT table1.question_id,
       SUM(IF(table1.correct_answer = 1, 1, 0)) AS correct_answers,
       SUM(IF(table1.correct_answer != 1, 1, 0)) AS incorrect_answers,
       round((SUM(IF(table1.correct_answer = 1, 1, 0)) / (SUM(IF(table1.correct_answer = 1, 1, 0)) + SUM(IF(table1.correct_answer != 1, 1, 0))) * 100),
             2) AS percentage
FROM table2 JOIN
     table1
     ON table2.answer_id = table1.id
group by table1.question_id
HAVING percentage BETWEEN 10 AND 20;

答案 1 :(得分:0)

要过滤聚合函数的结果,您需要使用HAVING子句,WHERE过滤器在这种情况下不起作用,如果您仍然希望在哪里执行,那么您必须重复整个where子句中的表达式

SELECT 
  table1.question_id,
  SUM(IF(table1.correct_answer = 1, 1, 0)) AS correct_answers,
  SUM(IF(table1.correct_answer != 1, 1, 0)) AS incorrect_answers,
  ROUND(
    (
      SUM(IF(table1.correct_answer = 1, 1, 0)) / (
        SUM(IF(table1.correct_answer = 1, 1, 0)) + SUM(IF(table1.correct_answer != 1, 1, 0))
      ) * 100
    ),
    2
  ) AS percentage 
FROM
  table2 
  JOIN table1 
    ON table2.answer_id = table1.id 
GROUP BY table1.question_id 
HAVING percentage BETWEEN 10 AND 20 
相关问题