Skip to content

Commit 1500ad7

Browse files
committed
solve: Medium faizanxmulla#13, #14
1 parent be9b26e commit 1500ad7

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
WITH cumulative_weights AS (
2+
SELECT id,
3+
SUM(weighting) OVER(ORDER BY id) AS cumulative_weight,
4+
SUM(weighting) OVER() AS total_weight
5+
FROM drivers
6+
)
7+
SELECT id
8+
FROM cumulative_weights
9+
WHERE cumulative_weight >= (
10+
SELECT rand() * total_weight
11+
FROM cumulative_weights
12+
LIMIT 1
13+
)
14+
ORDER BY cumulative_weight
15+
LIMIT 1
16+
17+
18+
19+
-- NOTE:
20+
21+
-- interesting and unique question. initially didnt have any idea how to even begin the question.
22+
-- use rand() in MySQL and random() in PostgresSQL.
23+
24+
-- for detailed explanation, here is the ChatGPT chat link:
25+
-- https://chatgpt.com/share/75b6430e-0120-49ec-aba2-be006f4d8d32
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
-- my solution:
2+
3+
WITH employees_cte as (
4+
SELECT id
5+
,salary
6+
,department_id
7+
,COUNT(*) OVER(PARTITION BY department_id) as number_of_employees
8+
FROM employees
9+
)
10+
SELECT DISTINCT name as department_name
11+
,number_of_employees
12+
,1.0 * COUNT(*) FILTER(WHERE salary > 100000) OVER(PARTITION BY department_id) / number_of_employees as percentage_over_100k
13+
FROM employees_cte e JOIN departments d ON d.id=e.department_id
14+
WHERE number_of_employees >= 10
15+
ORDER BY 3
16+
17+
18+
19+
-- official solution:
20+
21+
SELECT d.name as department_name
22+
,AVG(CASE WHEN salary > 100000 THEN 1 ELSE 0 END) AS percentage_over_100k
23+
,COUNT(*) AS number_of_employees
24+
FROM departments AS d JOIN employees AS e ON d.id = e.department_id
25+
GROUP BY 1
26+
HAVING COUNT(*) >= 10
27+
ORDER BY 1 DESC
28+
LIMIT 3
29+
30+
31+
32+
33+
-- NOTE:
34+
35+
-- solved on own and in first attempt.
36+
-- seeing the solution realized that I did it in a way complicated manner.
37+
38+
-- also, no need to use LEFT JOIN ; if the department has no employees, the condition ‘at least 10 employees’ won’t be satisfied.

0 commit comments

Comments
 (0)