简体   繁体   中英

How to find 1st Purchase date who made 2nd purchase within 30 days?

I need your quick help. I want to find a list of customer_id's and first purchase_date for customers who have made their second purchase within 30 days of their first purchase.

ie curstomer_id's 1,2,3 have made their 2nd purchase within 30 days.

I need curstomer_id's 1,2,3 and their respective first purchase_date.

I have more than 100k customer_id's.

在此处输入图片说明

If it can we achieved either in Python or SQL it would be great. Many Thanks:)

You can use window functions to get the first purchase and then count the number of purchases in the first 30 days:

select distinct customer_id, first_purchase_date
from (select t.*,
             min(purchase_date) over (partition by customer_id) as first_purchase_date
      from t
     ) t
where purchase_date <= first_purchase_date + interval '30 day' and
      purchase_date > first_purchase_date;

This uses standard SQL syntax. Date functions vary widely by database, so the syntax in your database might be slightly different.

I would like to see the number of purchases as well, so I would write this as:

select customer_id, first_purchase_date, count(*)
from (select t.*,
             min(purchase_date) over (partition by customer_id) as first_purchase_date
      from t
     ) t
where purchase_date <= first_purchase_date + interval '30 day' 
group by customer_id, first_purchase_date
having count(*) > 1;

Note: This is slightly different from the previous query. The first only counts a second purchase on a different day . This counts second purchases that might be on the first purchase date as well. I'm including both, because it is unclear which you actually want.

If you want to achieve this without window functions, you can just join your table with an old fashioned aggregate subquery, that returns the first purchase for each customer. It can also be a view or a CTE that does the same job.

SELECT DISTINCT customer_id, first_purchase_date
FROM Purchases AS P1 INNER JOIN
( 
   SELECT customer_id, min(purchase_date) AS first_purchase_date
   FROM Purchases 
   GROUP BY customer_id
) AS P2 ON P1.customer_id = P2.customer_id
WHERE purchase_date <= first_purchase_date + 30 days;

Like the previous contributor, I'm afraid I have no experience with the dbms you are using so I can't help with the expression you will need to use in order to compare the dates in the WHERE clause.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM