Skip to content
Advertisement

efficient way to find last week customer

I have 3 columns(customerid, date_purchased, item) table with 2 weeks of data. I want to retrieve the customers that only bought from the first week. My logic is to find the max date subtract it all the rest of the dates and retrieve customers where that difference equal or less than 7. Here is what I did, but I have a problem with my query.

   select distinct(customerid) from customer where datediff(max(date_purchased),Orderdate)<=7;

Advertisement

Answer

You could filter with a correlated subquery:

select distinct customerid
from customer
where date_purchased > (
    select max(date_purchased) - interval 7 day from customer
)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement