在SQL中的2个聚合字段上执行操作

时间:2016-01-15 19:41:50

标签: mysql sql rdbms

我正在尝试在下面的查询中显示四列:总回复计数,错误回复计数以及基于前两列的%错误。结果将按question_id分组。

SELECT 
    COUNT(correct) as total_resp,
    SUM(case when correct = 'f' then 1 else 0 end) as incor_resp,
    (incor_resp / total_resp) as percent_incor,
    question_id
FROM answers
WHERE student_id IN (
    SELECT id FROM students
    WHERE lang = 'es'
    LIMIT 50
)
GROUP BY question_id;

我的问题是,为什么上述percent_incor定义不起作用?我是否无法访问total_respincor_resp以便能够执行第3个字段定义的操作?如果没有,我怎么能在输出中包含这个字段?

谢谢!

5 个答案:

答案 0 :(得分:1)

不可能在同一个选择中通过别名引用其他字段。您需要再次重复表达式,或者您可以将select包装在另一个select中并在那里计算:

SELECT total_resp, incor_resp, incor_resp/total_resp as percent_incor
FROM (
    SELECT 
        COUNT(correct) as total_resp,
        SUM(case when correct = 'f' then 1 else 0 end) as incor_resp,
        (incor_resp / total_resp) as percent_incor,
        question_id
    FROM answers
    WHERE student_id IN (
        SELECT id FROM students
        WHERE lang = 'es'
        LIMIT 50
    )
    GROUP BY question_id
) t;

答案 1 :(得分:0)

你不能以SELECT COUNT(correct) as total_resp, SUM(case when correct = 'f' then 1 else 0 end) as incor_resp, (SUM(case when correct = 'f' then 1 else 0 end) / COUNT(correct)) as percent_incor, question_id FROM answers WHERE student_id IN ( SELECT id FROM students WHERE lang = 'es' LIMIT 50 ) GROUP BY question_id; 中的方式引用字段的别名。

试试这个:

=SUM(C4:N4)

答案 2 :(得分:0)

此代码是您正在寻找的吗?

SELECT 
COUNT(correct) as total_resp,
SUM(case when correct = 'f' then 1 else 0 end) as incor_resp,
(SUM(case when correct = 'f' then 1 else 0 end) / COUNT(correct)) as percent_incor,
question_id
FROM answers
WHERE student_id IN (
SELECT id FROM students
WHERE lang = 'es'
LIMIT 50
GROUP BY question_id;

答案 3 :(得分:0)

如果要使用别名,则必须访问子查询

SELECT total_resp, incor_resp, total_resp / incor_resp as percent_incor
FROM (
        SELECT 
                COUNT(correct) as total_resp,
                SUM(case when correct = 'f' then 1 else 0 end) as incor_resp,
                question_id
            FROM answers
            WHERE student_id IN (
                SELECT id FROM students
                WHERE lang = 'es'
                LIMIT 50
            )
            GROUP BY question_id
        ) T

答案 4 :(得分:0)

Coudl是案件sintax的问题​​

SELECT 
   COUNT(correct) as total_resp,
   SUM(case correct when 'f' then 1 else 0 end) as incor_resp,
   (incor_resp / total_resp) as percent_incor,
    question_id
FROM answers
WHERE student_id IN (
   SELECT id FROM students
   WHERE lang = 'es'
   LIMIT 50
)
GROUP BY question_id;