【问题标题】:Trying to get results based on another table - aggregate functions are not allowed in WHERE尝试基于另一个表获取结果 - WHERE 中不允许使用聚合函数
【发布时间】: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

【问题讨论】:

标签: sql postgresql


【解决方案1】:

要过滤聚合结果,您必须使用关键字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

【讨论】:

  • 。 . . Having 没有 GROUP BY ?
  • 对,甚至没有注意到原始查询中缺少它
  • 。 . .您当前的语法仍然无效。
  • 那你自己回答问题,请礼貌地惹恼别人回答的cmets
  • @YogeshSharma:您可以通过简单地编辑答案自己修复明显的拼写错误
猜你喜欢
  • 2017-06-16
  • 1970-01-01
  • 2017-07-17
  • 1970-01-01
  • 2014-01-26
  • 1970-01-01
  • 1970-01-01
  • 2021-08-31
  • 1970-01-01
相关资源
最近更新 更多