1
+ # create table orderss (order_id int,customer_id int,product_id int);
2
+ # insert into orderss VALUES (1, 1, 1),(1, 1, 2),(1, 1, 3),(2, 2, 1),(2, 2, 2),(2, 2, 4),(3, 1, 5)
3
+ # create table products (id int,name varchar(10));
4
+ # insert into products VALUES (1, 'A'),(2, 'B'),(3, 'C'),(4, 'D'),(5, 'E');
5
+
6
+ # Product recommendation. Just the basic type (“customers who bought this also bought…”).
7
+ # That, in its simplest form, is an outcome of basket analysis. In this video we will learn how to find products which are most
8
+ # frequently bought together using simple SQL. Based on the history ecommerce website can recommend products to new user.
9
+
10
+ select o1 .order_id ,o1 .product_id as p1,o2 .product_id as p2 from orderss o1
11
+ inner join orderss o2 on o1 .order_id = o2 .order_id
12
+ where o1 .order_id = 1 and o1 .product_id != o2 .product_id and o1 .product_id != o2 .product_id ;
13
+
14
+ select o1 .product_id as p1,o2 .product_id as p2 ,count (1 ) as purchase_frequency from orderss o1
15
+ inner join orderss o2 on o1 .order_id = o2 .order_id
16
+ where o1 .product_id < o2 .product_id
17
+ group by o1 .product_id ,o2 .product_id ;
18
+ # join with product table
19
+ select pr1 .name as p1,pr2 .name as p2,count (1 ) as purchase_frequency from orderss o1
20
+ inner join orderss o2 on o1 .order_id = o2 .order_id
21
+ inner join products pr1 on pr1 .id = o1 .product_id
22
+ inner join products pr2 on pr2 .id = o2 .product_id
23
+ where o1 .product_id < o2 .product_id
24
+ group by pr1 .name ,pr2 .name ;
25
+ # concatenate
26
+ select pr1 .name + ' ' + pr2 .name as pair,count (1 ) as purchase_frequency from orderss o1
27
+ inner join orderss o2 on o1 .order_id = o2 .order_id
28
+ inner join products pr1 on pr1 .id = o1 .product_id
29
+ inner join products pr2 on pr2 .id = o2 .product_id
30
+ where o1 .product_id < o2 .product_id
31
+ group by pr1 .name ,pr2 .name ;
32
+
33
+ select * from products;
0 commit comments