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

刷题记录帖子

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3278. Find Candidates for Data Scientist Position II
Medium
Topics
SQL Schema
Pandas Schema
Table: Candidates

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| candidate_id | int     |
| skill        | varchar |
| proficiency  | int     |
+--------------+---------+
(candidate_id, skill) is the unique key for this table.
Each row includes candidate_id, skill, and proficiency level (1-5).
Table: Projects

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| project_id   | int     |
| skill        | varchar |
| importance   | int     |
+--------------+---------+
(project_id, skill) is the primary key for this table.
Each row includes project_id, required skill, and its importance (1-5) for the project.
Leetcode is staffing for multiple data science projects. Write a solution to find the best candidate for each project based on the following criteria:

Candidates must have all the skills required for a project.
Calculate a score for each candidate-project pair as follows:
Start with 100 points
Add 10 points for each skill where proficiency > importance
Subtract 5 points for each skill where proficiency < importance
If the candidate's skill proficiency equal to the project's skill importance, the score remains unchanged
Include only the top candidate (highest score) for each project. If there’s a tie, choose the candidate with the lower candidate_id. If there is no suitable candidate for a project, do not return that project.

Return a result table ordered by project_id in ascending order.

The result format is in the following example.



Example:

Input:

Candidates table:

+--------------+-----------+-------------+
| candidate_id | skill     | proficiency |
+--------------+-----------+-------------+
| 101          | Python    | 5           |
| 101          | Tableau   | 3           |
| 101          | PostgreSQL| 4           |
| 101          | TensorFlow| 2           |
| 102          | Python    | 4           |
| 102          | Tableau   | 5           |
| 102          | PostgreSQL| 4           |
| 102          | R         | 4           |
| 103          | Python    | 3           |
| 103          | Tableau   | 5           |
| 103          | PostgreSQL| 5           |
| 103          | Spark     | 4           |
+--------------+-----------+-------------+
Projects table:

+-------------+-----------+------------+
| project_id  | skill     | importance |
+-------------+-----------+------------+
| 501         | Python    | 4          |
| 501         | Tableau   | 3          |
| 501         | PostgreSQL| 5          |
| 502         | Python    | 3          |
| 502         | Tableau   | 4          |
| 502         | R         | 2          |
+-------------+-----------+------------+
Output:

+-------------+--------------+-------+
| project_id  | candidate_id | score |
+-------------+--------------+-------+
| 501         | 101          | 105   |
| 502         | 102          | 130   |
+-------------+--------------+-------+
Explanation:

For Project 501, Candidate 101 has the highest score of 105. All other candidates have the same score but Candidate 101 has the lowest candidate_id among them.
For Project 502, Candidate 102 has the highest score of 130.
The output table is ordered by project_id in ascending order.
  1. # Write your MySQL query statement below
  2. WITH scored AS (
  3.     SELECT
  4.         p.project_id,
  5.         c.candidate_id,
  6.         100 + SUM(
  7.             CASE
  8.                 WHEN c.proficiency > p.importance THEN 10
  9.                 WHEN c.proficiency < p.importance THEN -5
  10.                 ELSE 0
  11.             END
  12.         ) AS score
  13.     FROM Projects p
  14.     JOIN (
  15.         SELECT project_id, COUNT(*) AS need
  16.         FROM Projects
  17.         GROUP BY project_id
  18.     ) r ON r.project_id = p.project_id
  19.     JOIN Candidates c ON c.skill = p.skill
  20.     GROUP BY p.project_id, c.candidate_id, r.need
  21.     HAVING COUNT(*) = r.need
  22. ),
  23. ranked AS (
  24.     SELECT
  25.         project_id,
  26.         candidate_id,
  27.         score,
  28.         ROW_NUMBER() OVER (
  29.             PARTITION BY project_id
  30.             ORDER BY score DESC, candidate_id ASC
  31.         ) AS rn
  32.     FROM scored
  33. )
  34. SELECT project_id, candidate_id, score
  35. FROM ranked
  36. WHERE rn = 1
  37. ORDER BY project_id;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3293. Calculate Product Final Price
Medium
Topics
SQL Schema
Pandas Schema
Table: Products

+------------+---------+
| Column Name| Type    |
+------------+---------+
| product_id | int     |
| category   | varchar |
| price      | decimal |
+------------+---------+
product_id is the unique key for this table.
Each row includes the product's ID, its category, and its price.
Table: Discounts

+------------+---------+
| Column Name| Type    |
+------------+---------+
| category   | varchar |
| discount   | int     |
+------------+---------+
category is the primary key for this table.
Each row contains a product category and the percentage discount applied to that category (values range from 0 to 100).
Write a solution to find the final price of each product after applying the category discount. If a product's category has no associated discount, its price remains unchanged.

Return the result table ordered by product_id in ascending order.

The result format is in the following example.



Example:

Input:

Products table:

+------------+-------------+-------+
| product_id | category    | price |
+------------+-------------+-------+
| 1          | Electronics | 1000  |
| 2          | Clothing    | 50    |
| 3          | Electronics | 1200  |
| 4          | Home        | 500   |
+------------+-------------+-------+
  
Discounts table:

+------------+----------+
| category   | discount |
+------------+----------+
| Electronics| 10       |
| Clothing   | 20       |
+------------+----------+
  
Output:

+------------+------------+-------------+
| product_id | final_price| category    |
+------------+------------+-------------+
| 1          | 900        | Electronics |
| 2          | 40         | Clothing    |
| 3          | 1080       | Electronics |
| 4          | 500        | Home        |
+------------+------------+-------------+
  
Explanation:

For product 1, it belongs to the Electronics category which has a 10% discount, so the final price is 1000 - (10% of 1000) = 900.
For product 2, it belongs to the Clothing category which has a 20% discount, so the final price is 50 - (20% of 50) = 40.
For product 3, it belongs to the Electronics category and receives a 10% discount, so the final price is 1200 - (10% of 1200) = 1080.
For product 4, no discount is available for the Home category, so the final price remains 500.
Result table is ordered by product_id in ascending order.
  1. # Write your MySQL query statement below
  2. SELECT
  3.     p.product_id,
  4.     p.price * (100 - COALESCE(d.discount, 0)) / 100 AS final_price,
  5.     p.category
  6. FROM Products p
  7. LEFT JOIN Discounts d
  8.   ON p.category = d.category
  9. ORDER BY p.product_id;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3308. Find Top Performing Driver
Medium
Topics
SQL Schema
Pandas Schema
Table: Drivers

+--------------+---------+
| Column Name  | Type    |
+--------------+---------+
| driver_id    | int     |
| name         | varchar |
| age          | int     |
| experience   | int     |
| accidents    | int     |
+--------------+---------+
(driver_id) is the unique key for this table.
Each row includes a driver's ID, their name, age, years of driving experience, and the number of accidents they’ve had.
Table: Vehicles

+--------------+---------+
| vehicle_id   | int     |
| driver_id    | int     |
| model        | varchar |
| fuel_type    | varchar |
| mileage      | int     |
+--------------+---------+
(vehicle_id, driver_id, fuel_type) is the unique key for this table.
Each row includes the vehicle's ID, the driver who operates it, the model, fuel type, and mileage.
Table: Trips

+--------------+---------+
| trip_id      | int     |
| vehicle_id   | int     |
| distance     | int     |
| duration     | int     |
| rating       | int     |
+--------------+---------+
(trip_id) is the unique key for this table.
Each row includes a trip's ID, the vehicle used, the distance covered (in miles), the trip duration (in minutes), and the passenger's rating (1-5).
Uber is analyzing drivers based on their trips. Write a solution to find the top-performing driver for each fuel type based on the following criteria:

A driver's performance is calculated as the average rating across all their trips. Average rating should be rounded to 2 decimal places.
If two drivers have the same average rating, the driver with the longer total distance traveled should be ranked higher.
If there is still a tie, choose the driver with the fewest accidents.
Return the result table ordered by fuel_type in ascending order.

The result format is in the following example.



Example:

Input:

Drivers table:

+-----------+----------+-----+------------+-----------+
| driver_id | name     | age | experience | accidents |
+-----------+----------+-----+------------+-----------+
| 1         | Alice    | 34  | 10         | 1         |
| 2         | Bob      | 45  | 20         | 3         |
| 3         | Charlie  | 28  | 5          | 0         |
+-----------+----------+-----+------------+-----------+
Vehicles table:

+------------+-----------+---------+-----------+---------+
| vehicle_id | driver_id | model   | fuel_type | mileage |
+------------+-----------+---------+-----------+---------+
| 100        | 1         | Sedan   | Gasoline  | 20000   |
| 101        | 2         | SUV     | Electric  | 30000   |
| 102        | 3         | Coupe   | Gasoline  | 15000   |
+------------+-----------+---------+-----------+---------+
Trips table:

+---------+------------+----------+----------+--------+
| trip_id | vehicle_id | distance | duration | rating |
+---------+------------+----------+----------+--------+
| 201     | 100        | 50       | 30       | 5      |
| 202     | 100        | 30       | 20       | 4      |
| 203     | 101        | 100      | 60       | 4      |
| 204     | 101        | 80       | 50       | 5      |
| 205     | 102        | 40       | 30       | 5      |
| 206     | 102        | 60       | 40       | 5      |
+---------+------------+----------+----------+--------+
Output:

+-----------+-----------+--------+----------+
| fuel_type | driver_id | rating | distance |
+-----------+-----------+--------+----------+
| Electric  | 2         | 4.50   | 180      |
| Gasoline  | 3         | 5.00   | 100      |
+-----------+-----------+--------+----------+
Explanation:

For fuel type Gasoline, both Alice (Driver 1) and Charlie (Driver 3) have trips. Charlie has an average rating of 5.0, while Alice has 4.5. Therefore, Charlie is selected.
For fuel type Electric, Bob (Driver 2) is the only driver with an average rating of 4.5, so he is selected.
The output table is ordered by fuel_type in ascending order.
  1. # Write your MySQL query statement below
  2. WITH stats AS (
  3.     SELECT
  4.         v.fuel_type,
  5.         v.driver_id,
  6.         ROUND(AVG(t.rating), 2) AS rating,
  7.         SUM(t.distance)         AS distance
  8.     FROM Vehicles v
  9.     JOIN Trips t
  10.       ON t.vehicle_id = v.vehicle_id
  11.     GROUP BY v.fuel_type, v.driver_id
  12. ),
  13. ranked AS (
  14.     SELECT
  15.         s.fuel_type,
  16.         s.driver_id,
  17.         s.rating,
  18.         s.distance,
  19.         ROW_NUMBER() OVER (
  20.             PARTITION BY s.fuel_type
  21.             ORDER BY s.rating DESC, s.distance DESC, d.accidents ASC
  22.         ) AS rn
  23.     FROM stats s
  24.     JOIN Drivers d
  25.       ON d.driver_id = s.driver_id
  26. )
  27. SELECT fuel_type, driver_id, rating, distance
  28. FROM ranked
  29. WHERE rn = 1
  30. ORDER BY fuel_type;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3322. Premier League Table Ranking III
Medium
Topics
SQL Schema
Pandas Schema
Table: SeasonStats

+------------------+---------+
| Column Name      | Type    |
+------------------+---------+
| season_id        | int     |
| team_id          | int     |
| team_name        | varchar |
| matches_played   | int     |
| wins             | int     |
| draws            | int     |
| losses           | int     |
| goals_for        | int     |
| goals_against    | int     |
+------------------+---------+
(season_id, team_id) is the unique key for this table.
This table contains season id, team id, team name, matches played, wins, draws, losses, goals scored (goals_for), and goals conceded (goals_against) for each team in each season.
Write a solution to calculate the points, goal difference, and position for each team in each season. The position ranking should be determined as follows:

Teams are first ranked by their total points (highest to lowest)
If points are tied, teams are then ranked by their goal difference (highest to lowest)
If goal difference is also tied, teams are then ranked alphabetically by team name
Points are calculated as follows:

3 points for a win
1 point for a draw
0 points for a loss
Goal difference is calculated as: goals_for - goals_against

Return the result table ordered by season_id in ascending order, then by position in ascending order, and finally by team_name in ascending order.

The query result format is in the following example.



Example:

Input:

SeasonStats table:

+------------+---------+-------------------+----------------+------+-------+--------+-----------+---------------+
| season_id  | team_id | team_name         | matches_played | wins | draws | losses | goals_for | goals_against |
+------------+---------+-------------------+----------------+------+-------+--------+-----------+---------------+
| 2021       | 1       | Manchester City   | 38             | 29   | 6     | 3      | 99        | 26            |
| 2021       | 2       | Liverpool         | 38             | 28   | 8     | 2      | 94        | 26            |
| 2021       | 3       | Chelsea           | 38             | 21   | 11    | 6      | 76        | 33            |
| 2021       | 4       | Tottenham         | 38             | 22   | 5     | 11     | 69        | 40            |
| 2021       | 5       | Arsenal           | 38             | 22   | 3     | 13     | 61        | 48            |
| 2022       | 1       | Manchester City   | 38             | 28   | 5     | 5      | 94        | 33            |
| 2022       | 2       | Arsenal           | 38             | 26   | 6     | 6      | 88        | 43            |
| 2022       | 3       | Manchester United | 38             | 23   | 6     | 9      | 58        | 43            |
| 2022       | 4       | Newcastle         | 38             | 19   | 14    | 5      | 68        | 33            |
| 2022       | 5       | Liverpool         | 38             | 19   | 10    | 9      | 75        | 47            |
+------------+---------+-------------------+----------------+------+-------+--------+-----------+---------------+
Output:

+------------+---------+-------------------+--------+-----------------+----------+
| season_id  | team_id | team_name         | points | goal_difference | position |
+------------+---------+-------------------+--------+-----------------+----------+
| 2021       | 1       | Manchester City   | 93     | 73              | 1        |
| 2021       | 2       | Liverpool         | 92     | 68              | 2        |
| 2021       | 3       | Chelsea           | 74     | 43              | 3        |
| 2021       | 4       | Tottenham         | 71     | 29              | 4        |
| 2021       | 5       | Arsenal           | 69     | 13              | 5        |
| 2022       | 1       | Manchester City   | 89     | 61              | 1        |
| 2022       | 2       | Arsenal           | 84     | 45              | 2        |
| 2022       | 3       | Manchester United | 75     | 15              | 3        |
| 2022       | 4       | Newcastle         | 71     | 35              | 4        |
| 2022       | 5       | Liverpool         | 67     | 28              | 5        |
+------------+---------+-------------------+--------+-----------------+----------+
Explanation:

For the 2021 season:
Manchester City has 93 points (29 * 3 + 6 * 1) and a goal difference of 73 (99 - 26).
Liverpool has 92 points (28 * 3 + 8 * 1) and a goal difference of 68 (94 - 26).
Chelsea has 74 points (21 * 3 + 11 * 1) and a goal difference of 43 (76 - 33).
Tottenham has 71 points (22 * 3 + 5 * 1) and a goal difference of 29 (69 - 40).
Arsenal has 69 points (22 * 3 + 3 * 1) and a goal difference of 13 (61 - 48).
For the 2022 season:
Manchester City has 89 points (28 * 3 + 5 * 1) and a goal difference of 61 (94 - 33).
Arsenal has 84 points (26 * 3 + 6 * 1) and a goal difference of 45 (88 - 43).
Manchester United has 75 points (23 * 3 + 6 * 1) and a goal difference of 15 (58 - 43).
Newcastle has 71 points (19 * 3 + 14 * 1) and a goal difference of 35 (68 - 33).
Liverpool has 67 points (19 * 3 + 10 * 1) and a goal difference of 28 (75 - 47).
The teams are ranked first by points, then by goal difference, and finally by team name.
The output is ordered by season_id ascending, then by rank ascending, and finally by team_name ascending.
  1. # Write your MySQL query statement below
  2. SELECT
  3.     season_id,
  4.     team_id,
  5.     team_name,
  6.     wins * 3 + draws AS points,
  7.     goals_for - goals_against AS goal_difference,
  8.     ROW_NUMBER() OVER (
  9.         PARTITION BY season_id
  10.         ORDER BY wins * 3 + draws DESC,
  11.                  goals_for - goals_against DESC,
  12.                  team_name ASC
  13.     ) AS position
  14. FROM SeasonStats
  15. ORDER BY season_id, position, team_name;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3328. Find Cities in Each State II
Medium
Topics
SQL Schema
Pandas Schema
Table: cities

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| state       | varchar |
| city        | varchar |
+-------------+---------+
(state, city) is the combination of columns with unique values for this table.
Each row of this table contains the state name and the city name within that state.
Write a solution to find all the cities in each state and analyze them based on the following requirements:

Combine all cities into a comma-separated string for each state.
Only include states that have at least 3 cities.
Only include states where at least one city starts with the same letter as the state name.
Return the result table ordered by the count of matching-letter cities in descending order and then by state name in ascending order.

The result format is in the following example.



Example:

Input:

cities table:

+--------------+---------------+
| state        | city          |
+--------------+---------------+
| New York     | New York City |
| New York     | Newark        |
| New York     | Buffalo       |
| New York     | Rochester     |
| California   | San Francisco |
| California   | Sacramento    |
| California   | San Diego     |
| California   | Los Angeles   |
| Texas        | Tyler         |
| Texas        | Temple        |
| Texas        | Taylor        |
| Texas        | Dallas        |
| Pennsylvania | Philadelphia  |
| Pennsylvania | Pittsburgh    |
| Pennsylvania | Pottstown     |
+--------------+---------------+
Output:

+-------------+-------------------------------------------+-----------------------+
| state       | cities                                    | matching_letter_count |
+-------------+-------------------------------------------+-----------------------+
| Pennsylvania| Philadelphia, Pittsburgh, Pottstown       | 3                     |
| Texas       | Dallas, Taylor, Temple, Tyler             | 3                     |
| New York    | Buffalo, Newark, New York City, Rochester | 2                     |
+-------------+-------------------------------------------+-----------------------+
Explanation:

Pennsylvania:
Has 3 cities (meets minimum requirement)
All 3 cities start with 'P' (same as state)
matching_letter_count = 3
Texas:
Has 4 cities (meets minimum requirement)
3 cities (Taylor, Temple, Tyler) start with 'T' (same as state)
matching_letter_count = 3
New York:
Has 4 cities (meets minimum requirement)
2 cities (Newark, New York City) start with 'N' (same as state)
matching_letter_count = 2
California is not included in the output because:
Although it has 4 cities (meets minimum requirement)
No cities start with 'C' (doesn't meet the matching letter requirement)
Note:

Results are ordered by matching_letter_count in descending order
When matching_letter_count is the same (Texas and New York both have 2), they are ordered by state name alphabetically
Cities in each row are ordered alphabetically
  1. # Write your MySQL query statement below
  2. SELECT
  3.     state,
  4.     GROUP_CONCAT(city ORDER BY city SEPARATOR ', ') AS cities,
  5.     SUM(LEFT(city, 1) = LEFT(state, 1))             AS matching_letter_count
  6. FROM cities
  7. GROUP BY state
  8. HAVING COUNT(*) >= 3
  9.    AND SUM(LEFT(city, 1) = LEFT(state, 1)) > 0
  10. ORDER BY matching_letter_count DESC, state ASC;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3358. Books with NULL Ratings
Easy
Topics
SQL Schema
Pandas Schema
Table: books

+----------------+---------+
| Column Name    | Type    |
+----------------+---------+
| book_id        | int     |
| title          | varchar |
| author         | varchar |
| published_year | int     |
| rating         | decimal |
+----------------+---------+
book_id is the unique key for this table.
Each row of this table contains information about a book including its unique ID, title, author, publication year, and rating.
rating can be NULL, indicating that the book hasn't been rated yet.
Write a solution to find all books that have not been rated yet (i.e., have a NULL rating).

Return the result table ordered by book_id in ascending order.

The result format is in the following example.



Example:

Input:

books table:

+---------+------------------------+------------------+----------------+--------+
| book_id | title                  | author           | published_year | rating |
+---------+------------------------+------------------+----------------+--------+
| 1       | The Great Gatsby       | F. Scott         | 1925           | 4.5    |
| 2       | To Kill a Mockingbird  | Harper Lee       | 1960           | NULL   |
| 3       | Pride and Prejudice    | Jane Austen      | 1813           | 4.8    |
| 4       | The Catcher in the Rye | J.D. Salinger    | 1951           | NULL   |
| 5       | Animal Farm            | George Orwell    | 1945           | 4.2    |
| 6       | Lord of the Flies      | William Golding  | 1954           | NULL   |
+---------+------------------------+------------------+----------------+--------+
Output:

+---------+------------------------+------------------+----------------+
| book_id | title                  | author           | published_year |
+---------+------------------------+------------------+----------------+
| 2       | To Kill a Mockingbird  | Harper Lee       | 1960           |
| 4       | The Catcher in the Rye | J.D. Salinger    | 1951           |
| 6       | Lord of the Flies      | William Golding  | 1954           |
+---------+------------------------+------------------+----------------+
Explanation:

The books with book_id 2, 4, and 6 have NULL ratings.
These books are included in the result table.
The other books (book_id 1, 3, and 5) have ratings and are not included.
The result is ordered by book_id in ascending order
  1. # Write your MySQL query statement below
  2. SELECT
  3.     book_id,
  4.     title,
  5.     author,
  6.     published_year
  7. FROM books
  8. WHERE rating IS NULL
  9. ORDER BY book_id;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3338. Second Highest Salary II
Medium
Topics
SQL Schema
Pandas Schema
Table: employees

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| emp_id      | int     |
| salary      | int     |
| dept        | varchar |
+-------------+---------+
emp_id is the unique key for this table.
Each row of this table contains information about an employee including their ID, salary, and department.
Write a solution to find the employees who earn the second-highest salary in each department. If multiple employees have the second-highest salary, include all employees with that salary.

Return the result table ordered by emp_id in ascending order.

The result format is in the following example.



Example:

Input:

employees table:

+--------+--------+-----------+
| emp_id | salary | dept      |
+--------+--------+-----------+
| 1      | 70000  | Sales     |
| 2      | 80000  | Sales     |
| 3      | 80000  | Sales     |
| 4      | 90000  | Sales     |
| 5      | 55000  | IT        |
| 6      | 65000  | IT        |
| 7      | 65000  | IT        |
| 8      | 50000  | Marketing |
| 9      | 55000  | Marketing |
| 10     | 55000  | HR        |
+--------+--------+-----------+
Output:

+--------+-----------+
| emp_id | dept      |
+--------+-----------+
| 2      | Sales     |
| 3      | Sales     |
| 5      | IT        |
| 8      | Marketing |
+--------+-----------+
Explanation:

Sales Department:
Highest salary is 90000 (emp_id: 4)
Second-highest salary is 80000 (emp_id: 2, 3)
Both employees with salary 80000 are included
IT Department:
Highest salary is 65000 (emp_id: 6, 7)
Second-highest salary is 55000 (emp_id: 5)
Only emp_id 5 is included as they have the second-highest salary
Marketing Department:
Highest salary is 55000 (emp_id: 9)
Second-highest salary is 50000 (emp_id: 8)
Employee 8 is included
HR Department:
Only has one employee
Not included in the result as it has fewer than 2 employees
  1. WITH ranked AS (
  2.     SELECT
  3.         emp_id,
  4.         dept,
  5.         DENSE_RANK() OVER (
  6.             PARTITION BY dept
  7.             ORDER BY salary DESC
  8.         ) AS rnk
  9.     FROM employees
  10. )
  11. SELECT emp_id, dept
  12. FROM ranked
  13. WHERE rnk = 2
  14. ORDER BY emp_id;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3401. Find Circular Gift Exchange Chains
Hard
Topics
SQL Schema
Pandas Schema
Table: SecretSanta

+-------------+------+
| Column Name | Type |
+-------------+------+
| giver_id    | int  |
| receiver_id | int  |
| gift_value  | int  |
+-------------+------+
(giver_id, receiver_id) is the unique key for this table.   
Each row represents a record of a gift exchange between two employees, giver_id represents the employee who gives a gift, receiver_id represents the employee who receives the gift and gift_value represents the value of the gift given.  
Write a solution to find the total gift value and length of circular chains of Secret Santa gift exchanges:

A circular chain is defined as a series of exchanges where:

Each employee gives a gift to exactly one other employee.
Each employee receives a gift from exactly one other employee.
The exchanges form a continuous loop (e.g., employee A gives a gift to B, B gives to C, and C gives back to A).
Return the result ordered by the chain length and total gift value of the chain in descending order. If multiple different chains have the same chain_length and total_gift_value, include that combination only once.

The result format is in the following example.



Example:

Input:

SecretSanta table:

+----------+-------------+------------+
| giver_id | receiver_id | gift_value |
+----------+-------------+------------+
| 1        | 2           | 20         |
| 2        | 3           | 30         |
| 3        | 1           | 40         |
| 4        | 5           | 25         |
| 5        | 4           | 35         |
+----------+-------------+------------+
Output:

+----------+--------------+------------------+
| chain_id | chain_length | total_gift_value |
+----------+--------------+------------------+
| 1        | 3            | 90               |
| 2        | 2            | 60               |
+----------+--------------+------------------+
Explanation:

Chain 1 involves employees 1, 2, and 3:
Employee 1 gives a gift to 2, employee 2 gives a gift to 3, and employee 3 gives a gift to 1.
Total gift value for this chain = 20 + 30 + 40 = 90.
Chain 2 involves employees 4 and 5:
Employee 4 gives a gift to 5, and employee 5 gives a gift to 4.
Total gift value for this chain = 25 + 35 = 60.
The result table is ordered by the chain length and total gift value of the chain in descending order.
  1. # Write your MySQL query statement below
  2. WITH RECURSIVE walk AS (
  3.     SELECT
  4.         giver_id                          AS start_id,
  5.         receiver_id                       AS cur,
  6.         1                                 AS len,
  7.         CAST(gift_value AS SIGNED)        AS total,
  8.         CAST(CONCAT(giver_id, ',', receiver_id) AS CHAR(2000)) AS path
  9.     FROM SecretSanta

  10.     UNION ALL

  11.     SELECT
  12.         w.start_id,
  13.         s.receiver_id,
  14.         w.len + 1,
  15.         w.total + s.gift_value,
  16.         CONCAT(w.path, ',', s.receiver_id)
  17.     FROM walk w
  18.     JOIN SecretSanta s
  19.       ON s.giver_id = w.cur
  20.     WHERE w.cur <> w.start_id                      -- already closed, stop
  21.       AND (s.receiver_id = w.start_id              -- closes the loop
  22.            OR NOT FIND_IN_SET(s.receiver_id, w.path))  -- no revisiting
  23. ),
  24. cycles AS (
  25.     SELECT DISTINCT
  26.         len   AS chain_length,
  27.         total AS total_gift_value
  28.     FROM walk
  29.     WHERE cur = start_id
  30. )
  31. SELECT
  32.     ROW_NUMBER() OVER (
  33.         ORDER BY chain_length DESC, total_gift_value DESC
  34.     ) AS chain_id,
  35.     chain_length,
  36.     total_gift_value
  37. FROM cycles
  38. ORDER BY chain_id;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3390. Longest Team Pass Streak
Hard
Topics
SQL Schema
Pandas Schema
Table: Teams

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| player_id   | int     |
| team_name   | varchar |
+-------------+---------+
player_id is the unique key for this table.
Each row contains the unique identifier for player and the name of one of the teams participating in that match.
Table: Passes

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| pass_from   | int     |
| time_stamp  | varchar |
| pass_to     | int     |
+-------------+---------+
(pass_from, time_stamp) is the unique key for this table.
pass_from is a foreign key to player_id from Teams table.
Each row represents a pass made during a match, time_stamp represents the time in minutes (00:00-90:00) when the pass was made,
pass_to is the player_id of the player receiving the pass.
Write a solution to find the longest successful pass streak for each team during the match. The rules are as follows:

A successful pass streak is defined as consecutive passes where:
Both the pass_from and pass_to players belong to the same team
A streak breaks when either:
The pass is intercepted (received by a player from the opposing team)
Return the result table ordered by team_name in ascending order.

The result format is in the following example.



Example:

Input:

Teams table:

+-----------+-----------+
| player_id | team_name |
+-----------+-----------+
| 1         | Arsenal   |
| 2         | Arsenal   |
| 3         | Arsenal   |
| 4         | Arsenal   |
| 5         | Chelsea   |
| 6         | Chelsea   |
| 7         | Chelsea   |
| 8         | Chelsea   |
+-----------+-----------+
Passes table:

+-----------+------------+---------+
| pass_from | time_stamp | pass_to |
+-----------+------------+---------+
| 1         | 00:05      | 2       |
| 2         | 00:07      | 3       |
| 3         | 00:08      | 4       |
| 4         | 00:10      | 5       |
| 6         | 00:15      | 7       |
| 7         | 00:17      | 8       |
| 8         | 00:20      | 6       |
| 6         | 00:22      | 5       |
| 1         | 00:25      | 2       |
| 2         | 00:27      | 3       |
+-----------+------------+---------+
Output:

+-----------+----------------+
| team_name | longest_streak |
+-----------+----------------+
| Arsenal   | 3              |
| Chelsea   | 4              |
+-----------+----------------+
Explanation:

Arsenal's streaks:
First streak: 3 passes (1→2→3→4) ended when player 4 passed to Chelsea's player 5
Second streak: 2 passes (1→2→3)
Longest streak = 3
Chelsea's streaks:
First streak: 3 passes (6→7→8→6→5)
Longest streak = 4
  1. WITH p AS (
  2.     SELECT
  3.         tf.team_name,
  4.         ps.time_stamp,
  5.         (tf.team_name = tt.team_name) AS ok
  6.     FROM Passes ps
  7.     JOIN Teams tf ON tf.player_id = ps.pass_from
  8.     JOIN Teams tt ON tt.player_id = ps.pass_to
  9. ),
  10. grouped AS (
  11.     SELECT
  12.         team_name,
  13.         ok,
  14.         SUM(1 - ok) OVER (
  15.             PARTITION BY team_name
  16.             ORDER BY time_stamp
  17.         ) AS grp
  18.     FROM p
  19. ),
  20. streaks AS (
  21.     SELECT team_name, grp, SUM(ok) AS len
  22.     FROM grouped
  23.     GROUP BY team_name, grp
  24. )
  25. SELECT
  26.     team_name,
  27.     MAX(len) AS longest_streak
  28. FROM streaks
  29. GROUP BY team_name
  30. HAVING MAX(len) > 0
  31. ORDER BY team_name;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3384. Team Dominance by Pass Success
Hard
Topics
SQL Schema
Pandas Schema
Table: Teams

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| player_id   | int     |
| team_name   | varchar |
+-------------+---------+
player_id is the unique key for this table.
Each row contains the unique identifier for player and the name of one of the teams participating in that match.

Table: Passes

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| pass_from   | int     |
| time_stamp  | varchar |
| pass_to     | int     |
+-------------+---------+
(pass_from, time_stamp) is the primary key for this table.
pass_from is a foreign key to player_id from Teams table.
Each row represents a pass made during a match, time_stamp represents the time in minutes (00:00-90:00) when the pass was made,
pass_to is the player_id of the player receiving the pass.

Write a solution to calculate the dominance score for each team in both halves of the match. The rules are as follows:

A match is divided into two halves: first half (00:00-45:00 minutes) and second half (45:01-90:00 minutes)
The dominance score is calculated based on successful and intercepted passes:
When pass_to is a player from the same team: +1 point
When pass_to is a player from the opposing team (interception): -1 point
A higher dominance score indicates better passing performance
Return the result table ordered by team_name and half_number in ascending order.

The result format is in the following example.



Example:

Input:

Teams table:

+------------+-----------+
| player_id  | team_name |
+------------+-----------+
| 1          | Arsenal   |
| 2          | Arsenal   |
| 3          | Arsenal   |
| 4          | Chelsea   |
| 5          | Chelsea   |
| 6          | Chelsea   |
+------------+-----------+
Passes table:

+-----------+------------+---------+
| pass_from | time_stamp | pass_to |
+-----------+------------+---------+
| 1         | 00:15      | 2       |
| 2         | 00:45      | 3       |
| 3         | 01:15      | 1       |
| 4         | 00:30      | 1       |
| 2         | 46:00      | 3       |
| 3         | 46:15      | 4       |
| 1         | 46:45      | 2       |
| 5         | 46:30      | 6       |
+-----------+------------+---------+
Output:

+-----------+-------------+-----------+
| team_name | half_number | dominance |
+-----------+-------------+-----------+
| Arsenal   | 1           | 3         |
| Arsenal   | 2           | 1         |
| Chelsea   | 1           | -1        |
| Chelsea   | 2           | 1         |
+-----------+-------------+-----------+
Explanation:

First Half (00:00-45:00):
Arsenal's passes:
1 → 2 (00:15): Successful pass (+1)
2 → 3 (00:45): Successful pass (+1)
3 → 1 (01:15): Successful pass (+1)
Chelsea's passes:
4 → 1 (00:30): Intercepted by Arsenal (-1)
Second Half (45:01-90:00):
Arsenal's passes:
2 → 3 (46:00): Successful pass (+1)
3 → 4 (46:15): Intercepted by Chelsea (-1)
1 → 2 (46:45): Successful pass (+1)
Chelsea's passes:
5 → 6 (46:30): Successful pass (+1)
The results are ordered by team_name and then half_number
  1. # Write your MySQL query statement below
  2. SELECT
  3.     tf.team_name,
  4.     CASE WHEN ps.time_stamp <= '45:00' THEN 1 ELSE 2 END AS half_number,
  5.     SUM(CASE WHEN tf.team_name = tt.team_name THEN 1 ELSE -1 END) AS dominance
  6. FROM Passes ps
  7. JOIN Teams tf ON tf.player_id = ps.pass_from
  8. JOIN Teams tt ON tt.player_id = ps.pass_to
  9. GROUP BY tf.team_name, half_number
  10. ORDER BY tf.team_name, half_number;
复制代码
回复

使用道具 举报

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

本版积分规则

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