楼主: Myron2017
跳转到指定楼层
上一主题 下一主题
收起左侧

刷题记录帖子

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3482. Analyze Organization Hierarchy
Hard
Topics
conpanies icon
Companies
SQL Schema
Pandas Schema
Table: Employees

+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| employee_id    | int     |
| employee_name  | varchar |
| manager_id     | int     |
| salary         | int     |
| department     | varchar |
+----------------+----------+
employee_id is the unique key for this table.
Each row contains information about an employee, including their ID, name, their manager's ID, salary, and department.
manager_id is null for the top-level manager (CEO).
Write a solution to analyze the organizational hierarchy and answer the following:

Hierarchy Levels: For each employee, determine their level in the organization (CEO is level 1, employees reporting directly to the CEO are level 2, and so on).
Team Size: For each employee who is a manager, count the total number of employees under them (direct and indirect reports).
Salary Budget: For each manager, calculate the total salary budget they control (sum of salaries of all employees under them, including indirect reports, plus their own salary).
Return the result table ordered by the result ordered by level in ascending order, then by budget in descending order, and finally by employee_name in ascending order.

The result format is in the following example.



Example:

Input:

Employees table:

+-------------+---------------+------------+--------+-------------+
| employee_id | employee_name | manager_id | salary | department  |
+-------------+---------------+------------+--------+-------------+
| 1           | Alice         | null       | 12000  | Executive   |
| 2           | Bob           | 1          | 10000  | Sales       |
| 3           | Charlie       | 1          | 10000  | Engineering |
| 4           | David         | 2          | 7500   | Sales       |
| 5           | Eva           | 2          | 7500   | Sales       |
| 6           | Frank         | 3          | 9000   | Engineering |
| 7           | Grace         | 3          | 8500   | Engineering |
| 8           | Hank          | 4          | 6000   | Sales       |
| 9           | Ivy           | 6          | 7000   | Engineering |
| 10          | Judy          | 6          | 7000   | Engineering |
+-------------+---------------+------------+--------+-------------+
Output:

+-------------+---------------+-------+-----------+--------+
| employee_id | employee_name | level | team_size | budget |
+-------------+---------------+-------+-----------+--------+
| 1           | Alice         | 1     | 9         | 84500  |
| 3           | Charlie       | 2     | 4         | 41500  |
| 2           | Bob           | 2     | 3         | 31000  |
| 6           | Frank         | 3     | 2         | 23000  |
| 4           | David         | 3     | 1         | 13500  |
| 7           | Grace         | 3     | 0         | 8500   |
| 5           | Eva           | 3     | 0         | 7500   |
| 9           | Ivy           | 4     | 0         | 7000   |
| 10          | Judy          | 4     | 0         | 7000   |
| 8           | Hank          | 4     | 0         | 6000   |
+-------------+---------------+-------+-----------+--------+
Explanation:

Organization Structure:
Alice (ID: 1) is the CEO (level 1) with no manager
Bob (ID: 2) and Charlie (ID: 3) report directly to Alice (level 2)
David (ID: 4), Eva (ID: 5) report to Bob, while Frank (ID: 6) and Grace (ID: 7) report to Charlie (level 3)
Hank (ID: 8) reports to David, and Ivy (ID: 9) and Judy (ID: 10) report to Frank (level 4)
Level Calculation:
The CEO (Alice) is at level 1
Each subsequent level of management adds 1 to the level
Team Size Calculation:
Alice has 9 employees under her (the entire company except herself)
Bob has 3 employees (David, Eva, and Hank)
Charlie has 4 employees (Frank, Grace, Ivy, and Judy)
David has 1 employee (Hank)
Frank has 2 employees (Ivy and Judy)
Eva, Grace, Hank, Ivy, and Judy have no direct reports (team_size = 0)
Budget Calculation:
Alice's budget: Her salary (12000) + all employees' salaries (72500) = 84500
Charlie's budget: His salary (10000) + Frank's budget (23000) + Grace's salary (8500) = 41500
Bob's budget: His salary (10000) + David's budget (13500) + Eva's salary (7500) = 31000
Frank's budget: His salary (9000) + Ivy's salary (7000) + Judy's salary (7000) = 23000
David's budget: His salary (7500) + Hank's salary (6000) = 13500
Employees with no direct reports have budgets equal to their own salary
Note:

The result is ordered first by level in ascending order
Within the same level, employees are ordered by budget in descending order then by name in ascending order
  1. # Write your MySQL query statement below
  2. WITH RECURSIVE closure AS (
  3.     SELECT employee_id AS anc, employee_id AS des
  4.     FROM Employees

  5.     UNION ALL

  6.     SELECT c.anc, e.employee_id
  7.     FROM closure c
  8.     JOIN Employees e
  9.       ON e.manager_id = c.des
  10. ),
  11. levels AS (
  12.     SELECT des AS employee_id, COUNT(*) AS level
  13.     FROM closure
  14.     GROUP BY des
  15. ),
  16. stats AS (
  17.     SELECT
  18.         c.anc            AS employee_id,
  19.         COUNT(*) - 1     AS team_size,
  20.         SUM(e.salary)    AS budget
  21.     FROM closure c
  22.     JOIN Employees e
  23.       ON e.employee_id = c.des
  24.     GROUP BY c.anc
  25. )
  26. SELECT
  27.     e.employee_id,
  28.     e.employee_name,
  29.     l.level,
  30.     s.team_size,
  31.     s.budget
  32. FROM Employees e
  33. JOIN levels l ON l.employee_id = e.employee_id
  34. JOIN stats  s ON s.employee_id = e.employee_id
  35. ORDER BY l.level ASC, s.budget DESC, e.employee_name ASC;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3832. Find Users with Persistent Behavior Patterns
Hard
SQL Schema
Pandas Schema
Table: activity

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| user_id      | int     |
| action_date  | date    |
| action       | varchar |
+--------------+---------+
(user_id, action_date, action) is the primary key (unique value) for this table.
Each row represents a user performing a specific action on a given date.
Write a solution to identify behaviorally stable users based on the following definition:

A user is considered behaviorally stable if there exists a sequence of at least 5 consecutive days such that:
The user performed exactly one action per day during that period.
The action is the same on all those consecutive days.
If a user has multiple qualifying sequences, only consider the sequence with the maximum length.
If multiple qualifying sequences have the same maximum length, consider the sequence with the lexicographically smallest action. If there is still a tie, consider the sequence with the latest start date.
Return the result table ordered by streak_length in descending order, then by user_id in ascending order.

The result format is in the following example.



Example:

Input:

activity table:

+---------+-------------+--------+
| user_id | action_date | action |
+---------+-------------+--------+
| 1       | 2024-01-01  | login  |
| 1       | 2024-01-02  | login  |
| 1       | 2024-01-03  | login  |
| 1       | 2024-01-04  | login  |
| 1       | 2024-01-05  | login  |
| 1       | 2024-01-06  | logout |
| 2       | 2024-01-01  | click  |
| 2       | 2024-01-02  | click  |
| 2       | 2024-01-03  | click  |
| 2       | 2024-01-04  | click  |
| 3       | 2024-01-01  | view   |
| 3       | 2024-01-02  | view   |
| 3       | 2024-01-03  | view   |
| 3       | 2024-01-04  | view   |
| 3       | 2024-01-05  | view   |
| 3       | 2024-01-06  | view   |
| 3       | 2024-01-07  | view   |
+---------+-------------+--------+
Output:

+---------+--------+---------------+------------+------------+
| user_id | action | streak_length | start_date | end_date   |
+---------+--------+---------------+------------+------------+
| 3       | view   | 7             | 2024-01-01 | 2024-01-07 |
| 1       | login  | 5             | 2024-01-01 | 2024-01-05 |
+---------+--------+---------------+------------+------------+
Explanation:

User 1:
Performed login from 2024-01-01 to 2024-01-05 on consecutive days
Each day has exactly one action, and the action is the same
Streak length = 5 (meets minimum requirement)
The action changes on 2024-01-06, ending the streak
User 2:
Performed click for only 4 consecutive days
Does not meet the minimum streak length of 5
Excluded from the result
User 3:
Performed view for 7 consecutive days
This is the longest valid sequence for this user
Included in the result
The Results table is ordered by streak_length in descending order, then by user_id in ascending order
  1. # Write your MySQL query statement below
  2. WITH single_day AS (
  3.     SELECT user_id, action_date, MIN(action) AS action
  4.     FROM activity
  5.     GROUP BY user_id, action_date
  6.     HAVING COUNT(*) = 1
  7. ),
  8. numbered AS (
  9.     SELECT
  10.         user_id,
  11.         action_date,
  12.         action,
  13.         ROW_NUMBER() OVER (
  14.             PARTITION BY user_id, action
  15.             ORDER BY action_date
  16.         ) AS rn
  17.     FROM single_day
  18. ),
  19. streaks AS (
  20.     SELECT
  21.         user_id,
  22.         action,
  23.         COUNT(*)         AS streak_length,
  24.         MIN(action_date) AS start_date,
  25.         MAX(action_date) AS end_date
  26.     FROM numbered
  27.     GROUP BY user_id, action, DATE_SUB(action_date, INTERVAL rn DAY)
  28.     HAVING COUNT(*) >= 5
  29. ),
  30. ranked AS (
  31.     SELECT
  32.         *,
  33.         ROW_NUMBER() OVER (
  34.             PARTITION BY user_id
  35.             ORDER BY streak_length DESC, action ASC, start_date DESC
  36.         ) AS rk
  37.     FROM streaks
  38. )
  39. SELECT user_id, action, streak_length, start_date, end_date
  40. FROM ranked
  41. WHERE rk = 1
  42. ORDER BY streak_length DESC, user_id ASC;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3808. Find Emotionally Consistent Users
Medium
SQL Schema
Pandas Schema
Table: reactions

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| user_id      | int     |
| content_id   | int     |
| reaction     | varchar |
+--------------+---------+
(user_id, content_id) is the primary key (unique value) for this table.
Each row represents a reaction given by a user to a piece of content.
Write a solution to identify emotionally consistent users based on the following requirements:

For each user, count the total number of reactions they have given.
Only include users who have reacted to at least 5 different content items.
A user is considered emotionally consistent if at least 60% of their reactions are of the same type.
Return the result table ordered by reaction_ratio in descending order and then by user_id in ascending order.

Note:

reaction_ratio should be rounded to 2 decimal places
The result format is in the following example.



Example:

Input:

reactions table:

+---------+------------+----------+
| user_id | content_id | reaction |
+---------+------------+----------+
| 1       | 101        | like     |
| 1       | 102        | like     |
| 1       | 103        | like     |
| 1       | 104        | wow      |
| 1       | 105        | like     |
| 2       | 201        | like     |
| 2       | 202        | wow      |
| 2       | 203        | sad      |
| 2       | 204        | like     |
| 2       | 205        | wow      |
| 3       | 301        | love     |
| 3       | 302        | love     |
| 3       | 303        | love     |
| 3       | 304        | love     |
| 3       | 305        | love     |
+---------+------------+----------+
Output:

+---------+-------------------+----------------+
| user_id | dominant_reaction | reaction_ratio |
+---------+-------------------+----------------+
| 3       | love              | 1.00           |
| 1       | like              | 0.80           |
+---------+-------------------+----------------+
Explanation:

User 1:
Total reactions = 5
like appears 4 times
reaction_ratio = 4 / 5 = 0.80
Meets the 60% consistency requirement
User 2:
Total reactions = 5
Most frequent reaction appears only 2 times
reaction_ratio = 2 / 5 = 0.40
Does not meet the consistency requirement
User 3:
Total reactions = 5
'love' appears 5 times
reaction_ratio = 5 / 5 = 1.00
Meets the consistency requirement
The Results table is ordered by reaction_ratio in descending order, then by user_id in ascending order.
  1. # Write your MySQL query statement below
  2. WITH per_reaction AS (
  3.     SELECT
  4.         user_id,
  5.         reaction,
  6.         COUNT(*) AS cnt,
  7.         SUM(COUNT(*)) OVER (PARTITION BY user_id) AS total
  8.     FROM reactions
  9.     GROUP BY user_id, reaction
  10. ),
  11. ranked AS (
  12.     SELECT
  13.         *,
  14.         ROW_NUMBER() OVER (
  15.             PARTITION BY user_id
  16.             ORDER BY cnt DESC, reaction ASC
  17.         ) AS rn
  18.     FROM per_reaction
  19. )
  20. SELECT
  21.     user_id,
  22.     reaction            AS dominant_reaction,
  23.     ROUND(cnt / total, 2) AS reaction_ratio
  24. FROM ranked
  25. WHERE rn = 1
  26.   AND total >= 5
  27.   AND cnt * 5 >= total * 3
  28. ORDER BY reaction_ratio DESC, user_id ASC;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3564. Seasonal Sales Analysis
Medium
Topics
SQL Schema
Pandas Schema
Table: sales

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| sale_id       | int     |
| product_id    | int     |
| sale_date     | date    |
| quantity      | int     |
| price         | decimal |
+---------------+---------+
sale_id is the unique identifier for this table.
Each row contains information about a product sale including the product_id, date of sale, quantity sold, and price per unit.
Table: products

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| product_id    | int     |
| product_name  | varchar |
| category      | varchar |
+---------------+---------+
product_id is the unique identifier for this table.
Each row contains information about a product including its name and category.
Write a solution to find the most popular product category for each season. The seasons are defined as:

Winter: December, January, February
Spring: March, April, May
Summer: June, July, August
Fall: September, October, November
The popularity of a category is determined by the total quantity sold in that season. If there is a tie, select the category with the highest total revenue (quantity × price). If there is still a tie, return the lexicographically smaller category.

Return the result table ordered by season in ascending order.

The result format is in the following example.



Example:

Input:

sales table:

+---------+------------+------------+----------+-------+
| sale_id | product_id | sale_date  | quantity | price |
+---------+------------+------------+----------+-------+
| 1       | 1          | 2023-01-15 | 5        | 10.00 |
| 2       | 2          | 2023-01-20 | 4        | 15.00 |
| 3       | 3          | 2023-03-10 | 3        | 18.00 |
| 4       | 4          | 2023-04-05 | 1        | 20.00 |
| 5       | 1          | 2023-05-20 | 2        | 10.00 |
| 6       | 2          | 2023-06-12 | 4        | 15.00 |
| 7       | 5          | 2023-06-15 | 5        | 12.00 |
| 8       | 3          | 2023-07-24 | 2        | 18.00 |
| 9       | 4          | 2023-08-01 | 5        | 20.00 |
| 10      | 5          | 2023-09-03 | 3        | 12.00 |
| 11      | 1          | 2023-09-25 | 6        | 10.00 |
| 12      | 2          | 2023-11-10 | 4        | 15.00 |
| 13      | 3          | 2023-12-05 | 6        | 18.00 |
| 14      | 4          | 2023-12-22 | 3        | 20.00 |
| 15      | 5          | 2024-02-14 | 2        | 12.00 |
+---------+------------+------------+----------+-------+
products table:

+------------+-----------------+----------+
| product_id | product_name    | category |
+------------+-----------------+----------+
| 1          | Warm Jacket     | Apparel  |
| 2          | Designer Jeans  | Apparel  |
| 3          | Cutting Board   | Kitchen  |
| 4          | Smart Speaker   | Tech     |
| 5          | Yoga Mat        | Fitness  |
+------------+-----------------+----------+
Output:

+---------+----------+----------------+---------------+
| season  | category | total_quantity | total_revenue |
+---------+----------+----------------+---------------+
| Fall    | Apparel  | 10             | 120.00        |
| Spring  | Kitchen  | 3              | 54.00         |
| Summer  | Tech     | 5              | 100.00        |
| Winter  | Apparel  | 9              | 110.00        |
+---------+----------+----------------+---------------+
Explanation:

Fall (Sep, Oct, Nov):
Apparel: 10 items sold (6 Jackets in Sep, 4 Jeans in Nov), revenue $120.00 (6×$10.00 + 4×$15.00)
Fitness: 3 Yoga Mats sold in Sep, revenue $36.00
Most popular: Apparel with highest total quantity (10)
Spring (Mar, Apr, May):
Kitchen: 3 Cutting Boards sold in Mar, revenue $54.00
Tech: 1 Smart Speaker sold in Apr, revenue $20.00
Apparel: 2 Warm Jackets sold in May, revenue $20.00
Most popular: Kitchen with highest total quantity (3) and highest revenue ($54.00)
Summer (Jun, Jul, Aug):
Apparel: 4 Designer Jeans sold in Jun, revenue $60.00
Fitness: 5 Yoga Mats sold in Jun, revenue $60.00
Kitchen: 2 Cutting Boards sold in Jul, revenue $36.00
Tech: 5 Smart Speakers sold in Aug, revenue $100.00
Most popular: Tech and Fitness both have 5 items, but Tech has higher revenue ($100.00 vs $60.00)
Winter (Dec, Jan, Feb):
Apparel: 9 items sold (5 Jackets in Jan, 4 Jeans in Jan), revenue $110.00
Kitchen: 6 Cutting Boards sold in Dec, revenue $108.00
Tech: 3 Smart Speakers sold in Dec, revenue $60.00
Fitness: 2 Yoga Mats sold in Feb, revenue $24.00
Most popular: Apparel with highest total quantity (9) and highest revenue ($110.00)
The result table is ordered by season in ascending order.
  1. # Write your MySQL query statement below
  2. WITH tagged AS (
  3.     SELECT
  4.         CASE
  5.             WHEN MONTH(s.sale_date) IN (12, 1, 2) THEN 'Winter'
  6.             WHEN MONTH(s.sale_date) IN (3, 4, 5)  THEN 'Spring'
  7.             WHEN MONTH(s.sale_date) IN (6, 7, 8)  THEN 'Summer'
  8.             ELSE 'Fall'
  9.         END AS season,
  10.         p.category,
  11.         s.quantity,
  12.         s.quantity * s.price AS revenue
  13.     FROM sales s
  14.     JOIN products p
  15.       ON p.product_id = s.product_id
  16. ),
  17. agg AS (
  18.     SELECT
  19.         season,
  20.         category,
  21.         SUM(quantity) AS total_quantity,
  22.         SUM(revenue)  AS total_revenue
  23.     FROM tagged
  24.     GROUP BY season, category
  25. ),
  26. ranked AS (
  27.     SELECT
  28.         *,
  29.         ROW_NUMBER() OVER (
  30.             PARTITION BY season
  31.             ORDER BY total_quantity DESC, total_revenue DESC, category ASC
  32.         ) AS rn
  33.     FROM agg
  34. )
  35. SELECT season, category, total_quantity, total_revenue
  36. FROM ranked
  37. WHERE rn = 1
  38. ORDER BY season;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3554. Find Category Recommendation Pairs
Hard
Topics
SQL Schema
Pandas Schema
Table: ProductPurchases

+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id     | int  |
| product_id  | int  |
| quantity    | int  |
+-------------+------+
(user_id, product_id) is the unique identifier for this table.
Each row represents a purchase of a product by a user in a specific quantity.
Table: ProductInfo

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_id  | int     |
| category    | varchar |
| price       | decimal |
+-------------+---------+
product_id is the unique identifier for this table.
Each row assigns a category and price to a product.
Amazon wants to understand shopping patterns across product categories. Write a solution to:

Find all category pairs (where category1 < category2)
For each category pair, determine the number of unique customers who purchased products from both categories
A category pair is considered reportable if at least 3 different customers have purchased products from both categories.

Return the result table of reportable category pairs ordered by customer_count in descending order, and in case of a tie, by category1 in ascending order lexicographically, and then by category2 in ascending order.

The result format is in the following example.



Example:

Input:

ProductPurchases table:

+---------+------------+----------+
| user_id | product_id | quantity |
+---------+------------+----------+
| 1       | 101        | 2        |
| 1       | 102        | 1        |
| 1       | 201        | 3        |
| 1       | 301        | 1        |
| 2       | 101        | 1        |
| 2       | 102        | 2        |
| 2       | 103        | 1        |
| 2       | 201        | 5        |
| 3       | 101        | 2        |
| 3       | 103        | 1        |
| 3       | 301        | 4        |
| 3       | 401        | 2        |
| 4       | 101        | 1        |
| 4       | 201        | 3        |
| 4       | 301        | 1        |
| 4       | 401        | 2        |
| 5       | 102        | 2        |
| 5       | 103        | 1        |
| 5       | 201        | 2        |
| 5       | 202        | 3        |
+---------+------------+----------+
ProductInfo table:

+------------+-------------+-------+
| product_id | category    | price |
+------------+-------------+-------+
| 101        | Electronics | 100   |
| 102        | Books       | 20    |
| 103        | Books       | 35    |
| 201        | Clothing    | 45    |
| 202        | Clothing    | 60    |
| 301        | Sports      | 75    |
| 401        | Kitchen     | 50    |
+------------+-------------+-------+
Output:

+-------------+-------------+----------------+
| category1   | category2   | customer_count |
+-------------+-------------+----------------+
| Books       | Clothing    | 3              |
| Books       | Electronics | 3              |
| Clothing    | Electronics | 3              |
| Electronics | Sports      | 3              |
+-------------+-------------+----------------+
Explanation:

Books-Clothing:
User 1 purchased products from Books (102) and Clothing (201)
User 2 purchased products from Books (102, 103) and Clothing (201)
User 5 purchased products from Books (102, 103) and Clothing (201, 202)
Total: 3 customers purchased from both categories
Books-Electronics:
User 1 purchased products from Books (102) and Electronics (101)
User 2 purchased products from Books (102, 103) and Electronics (101)
User 3 purchased products from Books (103) and Electronics (101)
Total: 3 customers purchased from both categories
Clothing-Electronics:
User 1 purchased products from Clothing (201) and Electronics (101)
User 2 purchased products from Clothing (201) and Electronics (101)
User 4 purchased products from Clothing (201) and Electronics (101)
Total: 3 customers purchased from both categories
Electronics-Sports:
User 1 purchased products from Electronics (101) and Sports (301)
User 3 purchased products from Electronics (101) and Sports (301)
User 4 purchased products from Electronics (101) and Sports (301)
Total: 3 customers purchased from both categories
Other category pairs like Clothing-Sports (only 2 customers: Users 1 and 4) and Books-Kitchen (only 1 customer: User 3) have fewer than 3 shared customers and are not included in the result.
The result is ordered by customer_count in descending order. Since all pairs have the same customer_count of 3, they are ordered by category1 (then category2) in ascending order.
  1. # Write your MySQL query statement below
  2. WITH user_cat AS (
  3.     SELECT DISTINCT
  4.         pp.user_id,
  5.         i.category
  6.     FROM ProductPurchases pp
  7.     JOIN ProductInfo i
  8.       ON i.product_id = pp.product_id
  9. )
  10. SELECT
  11.     a.category AS category1,
  12.     b.category AS category2,
  13.     COUNT(*)   AS customer_count
  14. FROM user_cat a
  15. JOIN user_cat b
  16.   ON a.user_id = b.user_id
  17. AND a.category < b.category
  18. GROUP BY a.category, b.category
  19. HAVING COUNT(*) >= 3
  20. ORDER BY customer_count DESC, category1 ASC, category2 ASC;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3521. Find Product Recommendation Pairs
Medium
Topics
conpanies icon
Companies
SQL Schema
Pandas Schema
Table: ProductPurchases

+-------------+------+
| Column Name | Type |
+-------------+------+
| user_id     | int  |
| product_id  | int  |
| quantity    | int  |
+-------------+------+
(user_id, product_id) is the unique key for this table.
Each row represents a purchase of a product by a user in a specific quantity.
Table: ProductInfo

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_id  | int     |
| category    | varchar |
| price       | decimal |
+-------------+---------+
product_id is the primary key for this table.
Each row assigns a category and price to a product.
Amazon wants to implement the Customers who bought this also bought... feature based on co-purchase patterns. Write a solution to :

Identify distinct product pairs frequently purchased together by the same customers (where product1_id < product2_id)
For each product pair, determine how many customers purchased both products
A product pair is considered for recommendation if at least 3 different customers have purchased both products.

Return the result table ordered by customer_count in descending order, and in case of a tie, by product1_id in ascending order, and then by product2_id in ascending order.

The result format is in the following example.



Example:

Input:

ProductPurchases table:

+---------+------------+----------+
| user_id | product_id | quantity |
+---------+------------+----------+
| 1       | 101        | 2        |
| 1       | 102        | 1        |
| 1       | 103        | 3        |
| 2       | 101        | 1        |
| 2       | 102        | 5        |
| 2       | 104        | 1        |
| 3       | 101        | 2        |
| 3       | 103        | 1        |
| 3       | 105        | 4        |
| 4       | 101        | 1        |
| 4       | 102        | 1        |
| 4       | 103        | 2        |
| 4       | 104        | 3        |
| 5       | 102        | 2        |
| 5       | 104        | 1        |
+---------+------------+----------+
ProductInfo table:

+------------+-------------+-------+
| product_id | category    | price |
+------------+-------------+-------+
| 101        | Electronics | 100   |
| 102        | Books       | 20    |
| 103        | Clothing    | 35    |
| 104        | Kitchen     | 50    |
| 105        | Sports      | 75    |
+------------+-------------+-------+
Output:

+-------------+-------------+-------------------+-------------------+----------------+
| product1_id | product2_id | product1_category | product2_category | customer_count |
+-------------+-------------+-------------------+-------------------+----------------+
| 101         | 102         | Electronics       | Books             | 3              |
| 101         | 103         | Electronics       | Clothing          | 3              |
| 102         | 104         | Books             | Kitchen           | 3              |
+-------------+-------------+-------------------+-------------------+----------------+
Explanation:

Product pair (101, 102):
Purchased by users 1, 2, and 4 (3 customers)
Product 101 is in Electronics category
Product 102 is in Books category
Product pair (101, 103):
Purchased by users 1, 3, and 4 (3 customers)
Product 101 is in Electronics category
Product 103 is in Clothing category
Product pair (102, 104):
Purchased by users 2, 4, and 5 (3 customers)
Product 102 is in Books category
Product 104 is in Kitchen category
The result is ordered by customer_count in descending order. For pairs with the same customer_count, they are ordered by product1_id and then product2_id in ascending order.
  1. # Write your MySQL query statement below
  2. SELECT
  3.     a.product_id AS product1_id,
  4.     b.product_id AS product2_id,
  5.     i1.category  AS product1_category,
  6.     i2.category  AS product2_category,
  7.     COUNT(*)     AS customer_count
  8. FROM ProductPurchases a
  9. JOIN ProductPurchases b
  10.   ON a.user_id = b.user_id
  11. AND a.product_id < b.product_id
  12. JOIN ProductInfo i1 ON i1.product_id = a.product_id
  13. JOIN ProductInfo i2 ON i2.product_id = b.product_id
  14. GROUP BY a.product_id, b.product_id, i1.category, i2.category
  15. HAVING COUNT(*) >= 3
  16. ORDER BY customer_count DESC, product1_id ASC, product2_id ASC;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3580. Find Consistently Improving Employees
Medium
Topics
SQL Schema
Pandas Schema
Table: employees

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| employee_id | int     |
| name        | varchar |
+-------------+---------+
employee_id is the unique identifier for this table.
Each row contains information about an employee.
Table: performance_reviews

+-------------+------+
| Column Name | Type |
+-------------+------+
| review_id   | int  |
| employee_id | int  |
| review_date | date |
| rating      | int  |
+-------------+------+
review_id is the unique identifier for this table.
Each row represents a performance review for an employee. The rating is on a scale of 1-5 where 5 is excellent and 1 is poor.
Write a solution to find employees who have consistently improved their performance over their last three reviews.

An employee must have at least 3 review to be considered
The employee's last 3 reviews must show strictly increasing ratings (each review better than the previous)
Use the most recent 3 reviews based on review_date for each employee
Calculate the improvement score as the difference between the latest rating and the earliest rating among the last 3 reviews
Return the result table ordered by improvement score in descending order, then by name in ascending order.

The result format is in the following example.



Example:

Input:

employees table:

+-------------+----------------+
| employee_id | name           |
+-------------+----------------+
| 1           | Alice Johnson  |
| 2           | Bob Smith      |
| 3           | Carol Davis    |
| 4           | David Wilson   |
| 5           | Emma Brown     |
+-------------+----------------+
performance_reviews table:

+-----------+-------------+-------------+--------+
| review_id | employee_id | review_date | rating |
+-----------+-------------+-------------+--------+
| 1         | 1           | 2023-01-15  | 2      |
| 2         | 1           | 2023-04-15  | 3      |
| 3         | 1           | 2023-07-15  | 4      |
| 4         | 1           | 2023-10-15  | 5      |
| 5         | 2           | 2023-02-01  | 3      |
| 6         | 2           | 2023-05-01  | 2      |
| 7         | 2           | 2023-08-01  | 4      |
| 8         | 2           | 2023-11-01  | 5      |
| 9         | 3           | 2023-03-10  | 1      |
| 10        | 3           | 2023-06-10  | 2      |
| 11        | 3           | 2023-09-10  | 3      |
| 12        | 3           | 2023-12-10  | 4      |
| 13        | 4           | 2023-01-20  | 4      |
| 14        | 4           | 2023-04-20  | 4      |
| 15        | 4           | 2023-07-20  | 4      |
| 16        | 5           | 2023-02-15  | 3      |
| 17        | 5           | 2023-05-15  | 2      |
+-----------+-------------+-------------+--------+
Output:

+-------------+----------------+-------------------+
| employee_id | name           | improvement_score |
+-------------+----------------+-------------------+
| 2           | Bob Smith      | 3                 |
| 1           | Alice Johnson  | 2                 |
| 3           | Carol Davis    | 2                 |
+-------------+----------------+-------------------+
Explanation:

Alice Johnson (employee_id = 1):
Has 4 reviews with ratings: 2, 3, 4, 5
Last 3 reviews (by date): 2023-04-15 (3), 2023-07-15 (4), 2023-10-15 (5)
Ratings are strictly increasing: 3 → 4 → 5
Improvement score: 5 - 3 = 2
Carol Davis (employee_id = 3):
Has 4 reviews with ratings: 1, 2, 3, 4
Last 3 reviews (by date): 2023-06-10 (2), 2023-09-10 (3), 2023-12-10 (4)
Ratings are strictly increasing: 2 → 3 → 4
Improvement score: 4 - 2 = 2
Bob Smith (employee_id = 2):
Has 4 reviews with ratings: 3, 2, 4, 5
Last 3 reviews (by date): 2023-05-01 (2), 2023-08-01 (4), 2023-11-01 (5)
Ratings are strictly increasing: 2 → 4 → 5
Improvement score: 5 - 2 = 3
Employees not included:
David Wilson (employee_id = 4): Last 3 reviews are all 4 (no improvement)
Emma Brown (employee_id = 5): Only has 2 reviews (needs at least 3)
The output table is ordered by improvement_score in descending order, then by name in ascending order.
  1. # Write your MySQL query statement below
  2. WITH ranked AS (
  3.     SELECT
  4.         employee_id,
  5.         rating,
  6.         ROW_NUMBER() OVER (
  7.             PARTITION BY employee_id
  8.             ORDER BY review_date DESC, review_id DESC
  9.         ) AS rn
  10.     FROM performance_reviews
  11. ),
  12. last3 AS (
  13.     SELECT
  14.         employee_id,
  15.         COUNT(*)                              AS cnt,
  16.         MAX(CASE WHEN rn = 1 THEN rating END) AS r1,  -- latest
  17.         MAX(CASE WHEN rn = 2 THEN rating END) AS r2,
  18.         MAX(CASE WHEN rn = 3 THEN rating END) AS r3   -- earliest of the three
  19.     FROM ranked
  20.     WHERE rn <= 3
  21.     GROUP BY employee_id
  22. )
  23. SELECT
  24.     e.employee_id,
  25.     e.name,
  26.     l.r1 - l.r3 AS improvement_score
  27. FROM last3 l
  28. JOIN employees e
  29.   ON e.employee_id = l.employee_id
  30. WHERE l.cnt = 3
  31.   AND l.r1 > l.r2
  32.   AND l.r2 > l.r3
  33. ORDER BY improvement_score DESC, e.name ASC;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3586. Find COVID Recovery Patients
Medium
Topics
conpanies icon
Companies
SQL Schema
Pandas Schema
Table: patients

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| patient_id  | int     |
| patient_name| varchar |
| age         | int     |
+-------------+---------+
patient_id is the unique identifier for this table.
Each row contains information about a patient.
Table: covid_tests

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| test_id     | int     |
| patient_id  | int     |
| test_date   | date    |
| result      | varchar |
+-------------+---------+
test_id is the unique identifier for this table.
Each row represents a COVID test result. The result can be Positive, Negative, or Inconclusive.
Write a solution to find patients who have recovered from COVID - patients who tested positive but later tested negative.

A patient is considered recovered if they have at least one Positive test followed by at least one Negative test on a later date
Calculate the recovery time in days as the difference between the first positive test and the first negative test after that positive test
Only include patients who have both positive and negative test results
Return the result table ordered by recovery_time in ascending order, then by patient_name in ascending order.

The result format is in the following example.



Example:

Input:

patients table:

+------------+--------------+-----+
| patient_id | patient_name | age |
+------------+--------------+-----+
| 1          | Alice Smith  | 28  |
| 2          | Bob Johnson  | 35  |
| 3          | Carol Davis  | 42  |
| 4          | David Wilson | 31  |
| 5          | Emma Brown   | 29  |
+------------+--------------+-----+
covid_tests table:

+---------+------------+------------+--------------+
| test_id | patient_id | test_date  | result       |
+---------+------------+------------+--------------+
| 1       | 1          | 2023-01-15 | Positive     |
| 2       | 1          | 2023-01-25 | Negative     |
| 3       | 2          | 2023-02-01 | Positive     |
| 4       | 2          | 2023-02-05 | Inconclusive |
| 5       | 2          | 2023-02-12 | Negative     |
| 6       | 3          | 2023-01-20 | Negative     |
| 7       | 3          | 2023-02-10 | Positive     |
| 8       | 3          | 2023-02-20 | Negative     |
| 9       | 4          | 2023-01-10 | Positive     |
| 10      | 4          | 2023-01-18 | Positive     |
| 11      | 5          | 2023-02-15 | Negative     |
| 12      | 5          | 2023-02-20 | Negative     |
+---------+------------+------------+--------------+
Output:

+------------+--------------+-----+---------------+
| patient_id | patient_name | age | recovery_time |
+------------+--------------+-----+---------------+
| 1          | Alice Smith  | 28  | 10            |
| 3          | Carol Davis  | 42  | 10            |
| 2          | Bob Johnson  | 35  | 11            |
+------------+--------------+-----+---------------+
Explanation:

Alice Smith (patient_id = 1):
First positive test: 2023-01-15
First negative test after positive: 2023-01-25
Recovery time: 25 - 15 = 10 days
Bob Johnson (patient_id = 2):
First positive test: 2023-02-01
Inconclusive test on 2023-02-05 (ignored for recovery calculation)
First negative test after positive: 2023-02-12
Recovery time: 12 - 1 = 11 days
Carol Davis (patient_id = 3):
Had negative test on 2023-01-20 (before positive test)
First positive test: 2023-02-10
First negative test after positive: 2023-02-20
Recovery time: 20 - 10 = 10 days
Patients not included:
David Wilson (patient_id = 4): Only has positive tests, no negative test after positive
Emma Brown (patient_id = 5): Only has negative tests, never tested positive
Output table is ordered by recovery_time in ascending order, and then by patient_name in ascending order.
  1. # Write your MySQL query statement below
  2. WITH first_pos AS (
  3.     SELECT patient_id, MIN(test_date) AS pos_date
  4.     FROM covid_tests
  5.     WHERE result = 'Positive'
  6.     GROUP BY patient_id
  7. ),
  8. recovery AS (
  9.     SELECT
  10.         f.patient_id,
  11.         DATEDIFF(MIN(c.test_date), f.pos_date) AS recovery_time
  12.     FROM first_pos f
  13.     JOIN covid_tests c
  14.       ON c.patient_id = f.patient_id
  15.      AND c.result = 'Negative'
  16.      AND c.test_date > f.pos_date
  17.     GROUP BY f.patient_id, f.pos_date
  18. )
  19. SELECT
  20.     p.patient_id,
  21.     p.patient_name,
  22.     p.age,
  23.     r.recovery_time
  24. FROM recovery r
  25. JOIN patients p
  26.   ON p.patient_id = r.patient_id
  27. ORDER BY r.recovery_time ASC, p.patient_name ASC;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3601. Find Drivers with Improved Fuel Efficiency
Medium
Topics
SQL Schema
Pandas Schema
Table: drivers

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| driver_id   | int     |
| driver_name | varchar |
+-------------+---------+
driver_id is the unique identifier for this table.
Each row contains information about a driver.
Table: trips

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| trip_id       | int     |
| driver_id     | int     |
| trip_date     | date    |
| distance_km   | decimal |
| fuel_consumed | decimal |
+---------------+---------+
trip_id is the unique identifier for this table.
Each row represents a trip made by a driver, including the distance traveled and fuel consumed for that trip.
Write a solution to find drivers whose fuel efficiency has improved by comparing their average fuel efficiency in the first half of the year with the second half of the year.

Calculate fuel efficiency as distance_km / fuel_consumed for each trip
First half: January to June, Second half: July to December
Only include drivers who have trips in both halves of the year
Calculate the efficiency improvement as (second_half_avg - first_half_avg)
Round all results to 2 decimal places
Return the result table ordered by efficiency improvement in descending order, then by driver name in ascending order.

The result format is in the following example.



Example:

Input:

drivers table:

+-----------+---------------+
| driver_id | driver_name   |
+-----------+---------------+
| 1         | Alice Johnson |
| 2         | Bob Smith     |
| 3         | Carol Davis   |
| 4         | David Wilson  |
| 5         | Emma Brown    |
+-----------+---------------+
trips table:

+---------+-----------+------------+-------------+---------------+
| trip_id | driver_id | trip_date  | distance_km | fuel_consumed |
+---------+-----------+------------+-------------+---------------+
| 1       | 1         | 2023-02-15 | 120.5       | 10.2          |
| 2       | 1         | 2023-03-20 | 200.0       | 16.5          |
| 3       | 1         | 2023-08-10 | 150.0       | 11.0          |
| 4       | 1         | 2023-09-25 | 180.0       | 12.5          |
| 5       | 2         | 2023-01-10 | 100.0       | 9.0           |
| 6       | 2         | 2023-04-15 | 250.0       | 22.0          |
| 7       | 2         | 2023-10-05 | 200.0       | 15.0          |
| 8       | 3         | 2023-03-12 | 80.0        | 8.5           |
| 9       | 3         | 2023-05-18 | 90.0        | 9.2           |
| 10      | 4         | 2023-07-22 | 160.0       | 12.8          |
| 11      | 4         | 2023-11-30 | 140.0       | 11.0          |
| 12      | 5         | 2023-02-28 | 110.0       | 11.5          |
+---------+-----------+------------+-------------+---------------+
Output:

+-----------+---------------+------------------+-------------------+------------------------+
| driver_id | driver_name   | first_half_avg   | second_half_avg   | efficiency_improvement |
+-----------+---------------+------------------+-------------------+------------------------+
| 2         | Bob Smith     | 11.24            | 13.33             | 2.10                   |
| 1         | Alice Johnson | 11.97            | 14.02             | 2.05                   |
+-----------+---------------+------------------+-------------------+------------------------+
Explanation:

Alice Johnson (driver_id = 1):
First half trips (Jan-Jun): Feb 15 (120.5/10.2 = 11.81), Mar 20 (200.0/16.5 = 12.12)
First half average efficiency: (11.81 + 12.12) / 2 = 11.97
Second half trips (Jul-Dec): Aug 10 (150.0/11.0 = 13.64), Sep 25 (180.0/12.5 = 14.40)
Second half average efficiency: (13.64 + 14.40) / 2 = 14.02
Efficiency improvement: 14.02 - 11.97 = 2.05
Bob Smith (driver_id = 2):
First half trips: Jan 10 (100.0/9.0 = 11.11), Apr 15 (250.0/22.0 = 11.36)
First half average efficiency: (11.11 + 11.36) / 2 = 11.24
Second half trips: Oct 5 (200.0/15.0 = 13.33)
Second half average efficiency: 13.33
Efficiency improvement: 13.33 - 11.24 = 2.10 (rounded to 2 decimal places)
Drivers not included:
Carol Davis (driver_id = 3): Only has trips in first half (Mar, May)
David Wilson (driver_id = 4): Only has trips in second half (Jul, Nov)
Emma Brown (driver_id = 5): Only has trips in first half (Feb)
The output table is ordered by efficiency improvement in descending order then by name in ascending order.
  1. WITH halves AS (
  2.     SELECT
  3.         d.driver_id,
  4.         d.driver_name,
  5.         AVG(CASE WHEN MONTH(t.trip_date) <= 6
  6.                  THEN t.distance_km / t.fuel_consumed END) AS f,
  7.         AVG(CASE WHEN MONTH(t.trip_date) >= 7
  8.                  THEN t.distance_km / t.fuel_consumed END) AS s
  9.     FROM drivers d
  10.     JOIN trips t
  11.       ON t.driver_id = d.driver_id
  12.     GROUP BY d.driver_id, d.driver_name
  13. )
  14. SELECT
  15.     driver_id,
  16.     driver_name,
  17.     ROUND(f, 2)     AS first_half_avg,
  18.     ROUND(s, 2)     AS second_half_avg,
  19.     ROUND(s - f, 2) AS efficiency_improvement
  20. FROM halves
  21. WHERE s > f
  22. ORDER BY efficiency_improvement DESC, driver_name ASC;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3611. Find Overbooked Employees
Medium
Topics
SQL Schema
Pandas Schema
Table: employees

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| employee_id   | int     |
| employee_name | varchar |
| department    | varchar |
+---------------+---------+
employee_id is the unique identifier for this table.
Each row contains information about an employee and their department.
Table: meetings

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| meeting_id    | int     |
| employee_id   | int     |
| meeting_date  | date    |
| meeting_type  | varchar |
| duration_hours| decimal |
+---------------+---------+
meeting_id is the unique identifier for this table.
Each row represents a meeting attended by an employee. meeting_type can be 'Team', 'Client', or 'Training'.
Write a solution to find employees who are meeting-heavy - employees who spend more than 50% of their working time in meetings during any given week.

Assume a standard work week is 40 hours
Calculate total meeting hours per employee per week (Monday to Sunday)
An employee is meeting-heavy if their weekly meeting hours > 20 hours (50% of 40 hours)
Count how many weeks each employee was meeting-heavy
Only include employees who were meeting-heavy for at least 2 weeks
Return the result table ordered by the number of meeting-heavy weeks in descending order, then by employee name in ascending order.

The result format is in the following example.



Example:

Input:

employees table:

+-------------+----------------+-------------+
| employee_id | employee_name  | department  |
+-------------+----------------+-------------+
| 1           | Alice Johnson  | Engineering |
| 2           | Bob Smith      | Marketing   |
| 3           | Carol Davis    | Sales       |
| 4           | David Wilson   | Engineering |
| 5           | Emma Brown     | HR          |
+-------------+----------------+-------------+
meetings table:

+------------+-------------+--------------+--------------+----------------+
| meeting_id | employee_id | meeting_date | meeting_type | duration_hours |
+------------+-------------+--------------+--------------+----------------+
| 1          | 1           | 2023-06-05   | Team         | 8.0            |
| 2          | 1           | 2023-06-06   | Client       | 6.0            |
| 3          | 1           | 2023-06-07   | Training     | 7.0            |
| 4          | 1           | 2023-06-12   | Team         | 12.0           |
| 5          | 1           | 2023-06-13   | Client       | 9.0            |
| 6          | 2           | 2023-06-05   | Team         | 15.0           |
| 7          | 2           | 2023-06-06   | Client       | 8.0            |
| 8          | 2           | 2023-06-12   | Training     | 10.0           |
| 9          | 3           | 2023-06-05   | Team         | 4.0            |
| 10         | 3           | 2023-06-06   | Client       | 3.0            |
| 11         | 4           | 2023-06-05   | Team         | 25.0           |
| 12         | 4           | 2023-06-19   | Client       | 22.0           |
| 13         | 5           | 2023-06-05   | Training     | 2.0            |
+------------+-------------+--------------+--------------+----------------+
Output:

+-------------+----------------+-------------+---------------------+
| employee_id | employee_name  | department  | meeting_heavy_weeks |
+-------------+----------------+-------------+---------------------+
| 1           | Alice Johnson  | Engineering | 2                   |
| 4           | David Wilson   | Engineering | 2                   |
+-------------+----------------+-------------+---------------------+
Explanation:

Alice Johnson (employee_id = 1):
Week of June 5-11 (2023-06-05 to 2023-06-11): 8.0 + 6.0 + 7.0 = 21.0 hours (> 20 hours)
Week of June 12-18 (2023-06-12 to 2023-06-18): 12.0 + 9.0 = 21.0 hours (> 20 hours)
Meeting-heavy for 2 weeks
David Wilson (employee_id = 4):
Week of June 5-11: 25.0 hours (> 20 hours)
Week of June 19-25: 22.0 hours (> 20 hours)
Meeting-heavy for 2 weeks
Employees not included:
Bob Smith (employee_id = 2): Week of June 5-11: 15.0 + 8.0 = 23.0 hours (> 20), Week of June 12-18: 10.0 hours (< 20). Only 1 meeting-heavy week
Carol Davis (employee_id = 3): Week of June 5-11: 4.0 + 3.0 = 7.0 hours (< 20). No meeting-heavy weeks
Emma Brown (employee_id = 5): Week of June 5-11: 2.0 hours (< 20). No meeting-heavy weeks
The result table is ordered by meeting_heavy_weeks in descending order, then by employee name in ascending order.
  1. # Write your MySQL query statement below
  2. WITH weekly AS (
  3.     SELECT
  4.         employee_id,
  5.         DATE_SUB(meeting_date, INTERVAL WEEKDAY(meeting_date) DAY) AS week_start,
  6.         SUM(duration_hours) AS hours
  7.     FROM meetings
  8.     GROUP BY employee_id, week_start
  9.     HAVING SUM(duration_hours) > 20
  10. )
  11. SELECT
  12.     e.employee_id,
  13.     e.employee_name,
  14.     e.department,
  15.     COUNT(*) AS meeting_heavy_weeks
  16. FROM weekly w
  17. JOIN employees e
  18.   ON e.employee_id = w.employee_id
  19. GROUP BY e.employee_id, e.employee_name, e.department
  20. HAVING COUNT(*) >= 2
  21. ORDER BY meeting_heavy_weeks DESC, e.employee_name ASC;
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表