我正在尝试编写一个查询,该查询将根据所有用户从另一张表中的捐款总和来选择所有用户,并按其捐款总和进行排序。但是我遇到了错误。我正在使用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
答案 0 :(得分: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