Skip to content
Advertisement

SQL to get all combination with intersection of events

I have a table(transaction) with consumer_id and item_id. I want to output all combinations of items and number of customers purchased both the item. How can this be done in SQL.

Transaction : 
consumer_id,item_id
Output:
item_1,item_2,purchased_together

Advertisement

Answer

I think you want a self-join:

select t1.item, t2.item, count(*) as num_customers
from transaction t1 join
     transaction t2
     on t1.consumer_id = t2.consumer_id and
        t1.item < t2.item
group by t1.item, t2.item
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement