[英]Trying to get results based on another table - aggregate functions are not allowed in WHERE
我正在嘗試編寫一個查詢,該查詢將根據他們從另一張表中獲得的捐款總額來選擇所有用戶,並按捐款總額進行排序。 但是我遇到了錯誤。 我正在使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.