Skip to content

Commit 1da7229

Browse files
committed
1 parent 838b848 commit 1da7229

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
WITH hist as (
2+
SELECT u.id, COUNT(c.user_id) AS frequency
3+
FROM users u LEFT JOIN comments c ON u.id=c.user_id
4+
GROUP BY 1
5+
),
6+
freq as (
7+
SELECT frequency, COUNT(*) AS num_users
8+
FROM hist
9+
GROUP BY 1
10+
)
11+
SELECT f1.frequency, SUM(f2.num_users) AS cum_total
12+
FROM freq f1 LEFT JOIN freq f2 ON f1.frequency >= f2.frequency
13+
GROUP BY 1
14+
15+
16+
17+
-- NOTE: was easy in hindsight but couldn't figure out on own.
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
SELECT ps.page_id as page,
2+
ps.postal_code,
3+
1.0 * COUNT(CASE WHEN ps.postal_code = u.postal_code THEN r.user_id ELSE null END) /
4+
COUNT(r.user_id) as percentage
5+
FROM page_sponsorships ps JOIN recommendations r ON ps.page_id=r.page_id
6+
JOIN users u ON r.user_id=u.id
7+
GROUP BY 1, 2
8+
ORDER BY 1
9+
10+
11+
-- my attempt:
12+
13+
SELECT ps.page_id, ps.postal_code, ROUND(1.0 * COUNT(user_id) / COUNT(*) OVER(), 1) as percentage
14+
FROM page_sponsorships ps JOIN recommendations r ON ps.page_id=r.page_id
15+
JOIN users u ON r.user_id=u.id and ps.postal_code=u.postal_code
16+
GROUP BY 1, 2
17+
18+
19+
20+
-- NOTE:
21+
22+
-- was using postal_code condition in the join itself, which was a mistake.
23+
-- also had to drop ROUND() function to pass second test case.

0 commit comments

Comments
 (0)