Market basket analysis by order details

I have a table that looks (abbreviated) as:

| order_id  | item_id   | amount    | qty   | date          |
|---------- |---------  |--------   |-----  |------------   |
| 1         | 1         | 10        | 1     | 10-10-2014    |
| 1         | 2         | 20        | 2     | 10-10-2014    |
| 2         | 1         | 10        | 1     | 10-12-2014    |
| 2         | 2         | 20        | 1     | 10-12-2014    |
| 2         | 3         | 45        | 1     | 10-12-2014    |
| 3         | 1         | 10        | 1     | 9-9-2014      |
| 3         | 3         | 45        | 1     | 9-9-2014      |
| 4         | 2         | 20        | 1     | 11-11-2014    |

I would like to run a query that will calculate a list of items that are most often found together.

In this case, the result will be:

|items|frequency|
|-----|---------|
|1,2, |2        |
|1,3  |1        |
|2,3  |1        |
|2    |1        |

Ideally, first presenting orders with more than one item, and then presenting the most frequently ordered individual items.

Can someone give an example of structuring this SQL?

+4
source share
2 answers

, , . , (2) ... UNION, , .

PostgreSQL 9.3

 create table orders(
        order_id int, 
        item_id int, 
        amount int, 
        qty int, 
        date timestamp


);

INSERT INTO ORDERS VALUES(1,1,10,1,'10-10-2014');
INSERT INTO ORDERS VALUES(1,2,20,1,'10-10-2014');
INSERT INTO ORDERS VALUES(2,1,10,1,'10-12-2014');
INSERT INTO ORDERS VALUES(2,2,20,1,'10-12-2014');
INSERT INTO ORDERS VALUES(2,3,45,1,'10-12-2014');
INSERT INTO ORDERS VALUES(3,1,10,1,'9-9-2014');
INSERT INTO ORDERS VALUES(3,3,45,1,'9-9-2014');
INSERT INTO ORDERS VALUES(4,2,10,1,'11-11-2014');

with order_pairs as (
    select (pg1.item_id, pg2.item_id) as items, pg1.date
    from 
    (select distinct item_id, date
    from orders) as pg1
    join
    (select distinct item_id, date
    from orders) as pg2
    ON 
    (
    pg1.date = pg2.date AND
    pg1.item_id != pg2.item_id AND
    pg1.item_id < pg2.item_id

    )
    )

    SELECT items, count(*) as frequency
    FROM order_pairs
    GROUP by items
    ORDER by items;

 items | frequency 
-------+-----------
 (1,2) |         2
 (1,3) |         2
 (2,3) |         1
(3 rows)
+1

. order_id , item_id < self.item_id. item_id . .

select items,count(*) as 'Freq' from 
(select concat(x.item_id,',',y.item_id) as items from orders x 
JOIN orders y ON x.order_id = y.order_id and 
x.item_id != y.item_id and x.item_id < y.item_id) A 
group by A.items order by A.items;
0

Source: https://habr.com/ru/post/1606019/


All Articles