我正在尝试编写一个单一的查询,根据他们从另一个表中捐赠的总和以及他们捐赠总额的顺序来选择所有用户。但是我收到了一个错误。我正在使用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
要过滤聚合结果,您必须使用关键字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