简体   繁体   中英

How to calculate customer retention in SQL based on events (not dates)?

I am trying to create a SQL Statement to find out which of the customer has NOT attended the last three events.

Table 1 - Customer:

Customer ID, Customer Name

Table 2 - Events

Event ID, Event Date, Event Name

Table 3 - Event Activity

Event ID, Customer ID

Now I am trying to find those customers that did not attend 3 events in a row.

Any help is appreciated.

Well, one method is to generate a list of all (of the last three) events and customers and then filter for customers who don't have them:

select c.customer_id
from customer c cross join
     (select e.*
      from events e
      order by event_date desc
      fetch first 3 rows only
     ) e left join
     event_activity ea
     on ea.customer_id = c.customer_id and ea.event_id = e.event_id
group by c.customer_id
having count(ea.event_id) < 3;

Another method would be to filter out customers who don't have all three:

select c.*
from customers c
where (select count(*)
        from event_activity ea join
             (select e.*
              from events e
              order by event_date desc
              fetch first 3 rows only
             ) e
             on e.event_id = ea.event_id
        where ea.customer_id = e.customer_id
       ) < 3;

If you are looking for customers that did not attend the most recent 3 events (assuming that's what you mean by "last three events")

select customer_id, customer_name
   from customers 
   where customer_id in  
      (select customer_id
       from event_activity 
       where event_id in
          (select event_id 
          from events_table
          where rownum <= 3
          order by event_date desc))

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