【问题标题】:Adding an aggregate function to the WHERE clause? [duplicate]向 WHERE 子句添加聚合函数? [复制]
【发布时间】:2014-07-28 23:21:08
【问题描述】:

我想制作一份报告,告诉所有在过去 75 天左右没有接到电话的客户。我的专栏如下。

Customer# Customer_Name Phone_Number Call_Date Salesman

呼叫日期会提取客户被呼叫的任何时间的日期。

这是我当前的查询。

select customer_no
      ,Customer_name
      ,Phone_number
      ,max(Call_Date) as Call_date
      ,Salesman
from salescalls
where call_date <= current_date - 75

我遇到的问题是,它会拉动每一位客户,并使用 75 天或更长时间前的最后一次呼叫。

例如,当最后通话日期为 2014 年 6 月 4 日时,它会拉起号码并将通话日期列为 2013 年 11 月 10 日。

它不应该列出过去 75 天内被呼叫的客户。所以为了防止这种情况,我试图在 where 子句中做到这一点。

Where max(call_date) <= current_date - 75

但这只是给我一个错误:

aggregates not allowed in WHERE clause

【问题讨论】:

  • 这么多重复。即使从今天开始。
  • 我可能应该放在那里,我到处寻找,但找不到可行的答案。
  • 从今天开始的骗子甚至几乎拥有相同的头衔。看看被骗的 cmets。
  • 你提出了一个体面的问题,就是这样。已删除反对票。不过,这仍然是一个骗局,我们尽量避免。

标签: sql postgresql aggregate-functions where


【解决方案1】:

你想要一个having 子句:

select customer_no, Customer_name, Phone_number, max(Call_Date) as Call_date,
       Salesman
from salescalls
group by customer_no, Customer_name, Phone_number, Salesman
having max(call_date) <= current_date - 75;

您不能将聚合函数放在where 子句中。

【讨论】:

    【解决方案2】:

    您需要将您的条件放在HAVING 子句中。

    having max(call_date) <= current_date - 75
    

    【讨论】:

    • 应该替换 where 子句吗?
    • yes..将你的条件转移到有子句,因为你的条件中有聚合函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-28
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多