【发布时间】:2019-04-10 20:45:32
【问题描述】:
我正在尝试编写一个查询,该查询将根据他们从另一个表中的捐赠总和选择所有用户,并按他们的捐赠总和排序。但我收到一个错误。我正在使用 postgres,但我想这同样适用于 mysql。
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过滤聚合数据。
标签: sql postgresql