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

Perform operation on 2 aggregated fields in SQL

我试图在下面的查询中显示四列:总响应数、不正确响应数以及基于前两列的 % 不正确响应。结果将按 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 以便能够针对第三个字段定义执行操作?如果没有,我怎样才能在我的输出中包含这个字段?

谢谢!

您不能像在 SELECT.

中那样引用字段的别名

试试这个:

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;

这段代码是您要找的吗?

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;

无法通过同一 select 中的别名引用其他字段。您需要再次重复表达式,或者您可以将 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;

如果您想使用别名,您必须访问子查询

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

大小写语法有问题

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;