将聚合函数添加到WHERE子句中?

时间:2014-07-28 23:21:09

标签: sql postgresql aggregate-functions where

我想制作一份报告,告诉所有过去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天或更多天。

例如,当最后一个通话日期是6/4/14时,它会提取数字,并将通话日期列为11/10/13。

不应列出在过去75天内调用过的客户。所以为了防止这种情况,我试图在where子句中这样做。

Where max(call_date) <= current_date - 75

但这只是给我一个错误:

aggregates not allowed in WHERE clause

2 个答案:

答案 0 :(得分:14)

您需要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子句中。

答案 1 :(得分:5)

您需要将条件放在HAVING条款中。

having max(call_date) <= current_date - 75
相关问题