【发布时间】:2019-06-20 01:04:15
【问题描述】:
在PostgreSQL 数据库中,我有一个名为answers 的表。此表存储有关用户如何回答问题的信息。表中只有 4 个问题。同时,回答问题的用户数量可以是动态的,用户只能回答部分问题。
表answers:
| EMPLOYEE | QUESTION_ID | QUESTION_TEXT | OPTION_ID | OPTION_TEXT |
|----------|-------------|------------------------|-----------|--------------|
| Bob | 1 | Do you like soup? | 1 | Yes |
| Alex | 1 | Do you like soup? | 2 | No |
| Kate | 1 | Do you like soup? | 3 | I don't know |
| Bob | 2 | Do you like ice cream? | 1 | Yes |
| Alex | 2 | Do you like ice cream? | 3 | I don't know |
| Oliver | 2 | Do you like ice cream? | 1 | Yes |
| Bob | 3 | Do you like summer? | 2 | No |
| Alex | 3 | Do you like summer? | 1 | Yes |
| Jack | 3 | Do you like summer? | 2 | No |
| Bob | 4 | Do you like winter? | 3 | I don't know |
| Alex | 4 | Do you like winter? | 1 | Yes |
| Oliver | 4 | Do you like winter? | 3 | I don't know |
例如,使用下一个代码,我可以找到回答这些问题的每个人的问题 1 和 2 的平均答案。
select
employee,
avg(
case when question_id in (1, 2) then option_id else null end
) as average_score
from
answers
group by
employee
结果:
| EMPLOYEE | AVERAGE_SCORE |
|----------|---------------|
| Bob | 2 |
| Alex | 2,5 |
| Kate | 3 |
| Oliver | 1 |
现在,我想知道问题 1 和 2 的答案平均值 >= 大于 2 的用户数量。我尝试了下一个代码,但它引发了错误:
select
count(
avg(
case when question_id in (1, 2) then option_id else null end
)
) as average_score
from
answers
where
average_score >= 2
group by
answers.employee
错误:
SQL Error [42803]: ERROR: aggregate function calls cannot be nested
【问题讨论】:
标签: sql postgresql