sql - 向 WHERE 子句添加聚合函数?

标签 sql postgresql aggregate-functions where-clause

<分区>

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

Customer# Customer_Name Phone_Number Call_Date 销售员

调用日期会提取任何和每次调用客户的日期。

这是我当前的查询。

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

最佳答案

你想要一个 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 子句中。

关于sql - 向 WHERE 子句添加聚合函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25005865/

相关文章:

sql - 核心数据关系与基于服务器的外键

python - 如何在 Sqlalchemy 中正确使用 SQL 连接/子查询

mysql - MySql 查询非空约束时出错

SQL - 从表中获取并与同一个表连接

sql - 解释分析语句中的循环是什么意思?

php - mysql - 列计数与行的值计数不匹配

sql - 为什么QueryRow()。Scan()在表中不为空时返回空字符串?

python - 计算数据帧中特定列(SUM、AVG、STDEV)的所有嵌套级别聚合

sql - 复合类型数组上的 SUM 和 GROUP BY

arrays - 在 plpgsql 函数中返回匹配输入数组元素的行