Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 0e77c5e

Browse files
authoredSep 24, 2020
Create the-most-frequently-ordered-products-for-each-customer.sql
1 parent 852547d commit 0e77c5e

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
 
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
WITH product_count_cte AS
5+
(SELECT c.customer_id,
6+
o.product_id,
7+
p.product_name,
8+
count(c.customer_id) AS product_cnt
9+
FROM Customers c,
10+
Orders o,
11+
Products p
12+
WHERE c.customer_id = o.customer_id
13+
AND o.product_id = p.product_id
14+
GROUP BY c.customer_id,
15+
o.product_id
16+
ORDER BY NULL)
17+
, max_product_count_cte AS
18+
(SELECT customer_id,
19+
max(product_cnt) AS product_cnt
20+
FROM product_count_cte
21+
GROUP BY customer_id
22+
ORDER BY NULL)
23+
24+
SELECT a.customer_id,
25+
a.product_id,
26+
a.product_name
27+
FROM product_count_cte a
28+
INNER JOIN max_product_count_cte b
29+
ON a.customer_id = b.customer_id AND
30+
a.product_cnt = b.product_cnt;

0 commit comments

Comments
 (0)
Please sign in to comment.