如何在查询中正确使用AVG?

时间:2019-07-03 03:14:35

标签: sql postgresql

PostgreSQL数据库中,有一个名为answers的表,看起来像这样:

| EMPLOYEE | QUESTION_ID | QUESTION_TEXT          | OPTION_ID | OPTION_TEXT  |
|----------|-------------|------------------------|-----------|--------------|
| Bob      | 1           | Do you like soup?      | 1         | 1            |
| Alex     | 1           | Do you like soup?      | 9         | 9            |
| Oliver   | 1           | Do you like soup?      | 6         | 6            |
| Bob      | 2           | Do you like ice cream? | 3         | 3            |
| Alex     | 2           | Do you like ice cream? | 9         | 9            |
| Oliver   | 2           | Do you like ice cream? | 8         | 8            |
| Bob      | 3           | Do you like summer?    | 2         | 2            |
| Alex     | 3           | Do you like summer?    | 9         | 9            | 
| Oliver   | 3           | Do you like summer?    | 8         | 8            |

在此表中,您可以注意到我有3个问题和用户答案。用户回答问题的比例为1到10。我试图找到没有深层子查询的问题1、2和3的平均答案大于5的用户数。例如,只有2个用户对三个问题的回答avg(option_text)大于5。他们是Alex和Oliver。

我尝试使用此脚本,但是它的工作与预期不同:

SELECT
    SUM(CASE WHEN (AVG(OPTION_ID) FILTER(WHERE QUESTION_ID IN(61, 62))) > 5 THEN 1 ELSE 0 END) AS COUNT
FROM
    ANSWERS;

错误

SQL Error [42803]: ERROR: aggregate function calls cannot be nested

2 个答案:

答案 0 :(得分:1)

您可以选择每个问题的平均答案大于5的所有员工1,2,3,并按查询分组

select employee, avg(option_id)
from answers
where question_id in (1,2,3)
group by employee
having avg(option_id) > 5
and count(distinct question_id) = 3 
-- the last part is only needed if you only want employees that answered all questions

计算平均值大于5的用户数

select count(*) from (
    select employee
    from answers
    where question_id in (1,2,3)
    group by employee
    having avg(option_id) > 5
    and count(distinct question_id) = 3
)

答案 1 :(得分:0)

以下查询应能正常工作

SELECT
DISTINCT COUNT(*) OVER () AS CNT
FROM ANSWERS
WHERE QUESTION_ID NOT IN(61, 62)
GROUP BY EMPLOYEE
HAVING AVG(OPTION_ID) > 5

查看演示Here

相关问题