Product pairs most often bought together
MediumP3Coding
Table order_items:
| Column | Type |
|---|---|
| order_id | int |
| product_id | int |
(order_id, product_id) is unique. Find the 3 pairs of products that appear together in the most orders. A pair is two different products in the same order, written with the smaller id first, and counted once per order.
Sort by number of orders (highest first), then by product_a, then product_b. Return at most 3 rows.
Output columns: product_a, product_b, order_count.
Schema
CREATE TABLE order_items ( order_id int NOT NULL, product_id int NOT NULL, PRIMARY KEY (order_id, product_id) );
Example 1
- Input
- orders: 1 = {1, 2, 3}, 2 = {1, 2}, 3 = {2, 3}, 4 = {1, 2}
- Output
- (1, 2, 3), (2, 3, 2), (1, 3, 1)
Constraints
- PostgreSQL dialect.
Hints
Give it a real attempt first. Run shows which examples fail.
Saved automatically
PostgreSQL
Run checks the 3 visible tests, Submit all 6. ⌘Enter runs, ⌘⇧Enter submits.