-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataExpert-SQL12.sql
More file actions
34 lines (30 loc) · 805 Bytes
/
Copy pathDataExpert-SQL12.sql
File metadata and controls
34 lines (30 loc) · 805 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
-- Question: Top Reviewed Customers per Product
-- https://www.dataexpert.io/question/top-reviewed-customers-per-product
-- Approach 1: Using GROUP BY
SELECT
product_id,
customer_id,
MAX(review_score) AS review_score,
MAX(helpful_votes) AS helpful_votes
FROM playground.product_reviews
GROUP BY product_id, customer_id
ORDER BY product_id;
-- Approach 2: Using CTE AND RANK()
WITH top_reviewed AS (
SELECT
product_id,
customer_id,
review_score,
helpful_votes,
RANK() OVER(PARTITION BY product_id, customer_id
ORDER BY review_score DESC, helpful_votes) AS rnk
FROM playground.product_reviews
)
SELECT
product_id,
customer_id,
review_score,
helpful_votes
FROM top_reviewed
WHERE rnk = 1
ORDER BY product_id;