尝试基于另一个表获取结果 - WHERE中不允许聚合函数

问题描述 投票:1回答:1

我正在尝试编写一个单一的查询,根据他们从另一个表中捐赠的总和以及他们捐赠总额的顺序来选择所有用户。但是我收到了一个错误。我正在使用postgres,但我想同样适用于mysqql。

ERROR:  aggregate functions are not allowed in WHERE
LINE 8:  sum(donations.donation) = 400
         ^

用户表

id |   username   |
1     Larry Page
2     Sergey Brin

捐款表

id | user_id | donation |     date
1      1         100       2019-02-12
2      1         200       2019-02-13
3      2         500       2019-01-15
4      1         100       2019-04-10

这是我的查询

select
    users.username, sum(donations.donation) as donation_sum
from
    users
inner join donations
    on users.id = donations.user_id
where
    sum(donations.donation) = 400
and
    donations.date between '2019-01-01' and '2019-12-31'
order by
    donation_sum

我期待结果是这样的

username    |  donation_sum
Larry Page        400
sql postgresql
1个回答
2
投票

要过滤聚合结果,您必须使用关键字HAVING

select
    users.username, sum(donations.donation) as donation_sum
from
    users
inner join donations
    on users.id = donations.user_id
where
    donations.date between '2019-01-01' and '2019-12-31'
group by
    users.username
having
    sum(donations.donation) = 400
order by
    donation_sum
© www.soinside.com 2019 - 2024. All rights reserved.