Skip to content
Advertisement

How to find the category that is both ordered & clicked by customer joining multiple tables?

I have these below 5 tables and I am trying to find customers that ordered from the same category they clicked. With a condition where order date should be greater than the click date

Table: customers

email           cid         
a@gmail.com     1001            
b@gmail.com     1002            
c@gmail.com     1003
            

Table : orders

cid     pid     order_date      
1001    4000    Aug-1-2021      
1002    5000    Aug-1-2021      
1003    4000    Aug-1-2021  

Table : clicks

cid     pid     click_date      
1001    4000    Jul-1-2021      
1002    8000    Jul-1-2021      
1003    8000    Jul-1-2021  

Table : product

pid     category_id         
4000    1           
8000    2           
5000    2           

Table : dim

categorty_id    category            
1               Games           
2               Books           
3               Music   

Expected results

email           cid     category_clicked    category_ordered
a@gmail.com     1001    games               games
b@gmail.com     1002    books               books 

c@gmail will be excluded because he ordered a different category than the one he clicked. I am not able to get how to fetch the data based on the category. I was only able to write a query to fetch if customers bought the same item they clicked. Any help is appreciated. This is the query i have to find exactly what customer clicked & bought the same pid.

select distinct cust.email
From customers cust

Join orders o
on cust.cid=o.cid
join clicks c
on c.cid=o.cid and c.pid=o.pid

Join product prod
ON c.pid=prod.pid

inner join dim dim
on dim.category_id=prod.category_id
where o.order_date>=c.click_date

Advertisement

Answer

1. t1: join between the customers table and the orders and product

2. t2: join between the customers table and the clicks and product

3. result join t1 to t2 with t1.cid = t2.cid and t1.categorty_id = t2.categorty_id

4. join t1 to dim


select  t1.email, t1.cid,  dim.category as category_clicked, dim.category as category_ordered 
From 
  (select cust.*,o.pid,o.order_date,prod.categorty_id
  from customers cust
  Join orders o on cust.cid=o.cid
  Join product prod on o.pid=prod.pid) t1


join (select cust.*,c.pid,c.click_date,prod.categorty_id
     from customers cust
     Join clicks c on cust.cid=c.cid
     Join product prod on c.pid=prod.pid ) t2 
on t1.cid = t2.cid and t1.categorty_id = t2.categorty_id
     
join dim on dim.categorty_id= t1.categorty_id
where t2.click_date <= t1.order_date;

demo in db<>fiddle

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement