I want to make a report that tells all the customers that haven't been called in the last 75 or so days. My columns are as follows.
Customer# Customer_Name Phone_Number Call_Date Salesman
The call date pulls up the dates of any and every time the customer has been called.
Here's my current query.
select customer_no
,Customer_name
,Phone_number
,max(Call_Date) as Call_date
,Salesman
from salescalls
where call_date <= current_date - 75
The problem I'm having is that it is pulling every single customer and using the last time they were called 75 or more days ago.
For example when the last call date is 6/4/14, it pulls the number up and lists the call date as 11/10/13.
It isn't supposed to list customers that have been called within the last 75 days. So to prevent this, I'm trying to do this in the where clause.
Where max(call_date) <= current_date - 75
But this just gives me an error:
aggregates not allowed in WHERE clause
You can't use an aggregate directly in a WHERE clause; that's what HAVING clauses are for. You can use a sub-query which contains an aggregate in the WHERE clause. In SQL Server how do you return the number of rows affected by an UPDATE statement? @@ROWCOUNT (Transact-SQL) - SQL Server Which of the following are SQL aggregate functions?
Aggregates are evaluated after the WHERE clause been processed, so the aggregate values are not yet available unless they are in a subquery (which is not efficient). HAVING clauses, which are evaluated after WHERE and GROUP BY, are able to use the aggregates and are similar to WHERE in function.
These types of functions are called “aggregate functions” because they perform a function upon the aggregation of values in a field. The grouping and aggregate function choices available in the drop-down in the “Total” row in Access include “Group By,” for grouping fields, and a variety of standard, aggregate functions.
If you are using an aggregate function in a where clause then it means you want to filter data on the basis of that aggregation function. In my case, it's SUM (). I'll jump to the solution. The inner query is used to fetch results that need to be filtered.
You want a having
clause:
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;
You can't put aggregation functions in a where
clause.
You need to put your condition in HAVING clause.
having max(call_date) <= current_date - 75
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With