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

刷题记录帖子

🔗
 楼主| Myron2017 2026-11-23 12:30:31 | 只看该作者
全局:
3198. Find Cities in Each State
Easy
Topics
SQL Schema
Pandas Schema
Table: cities

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| state       | varchar |
| city        | varchar |
+-------------+---------+
(state, city) is the primary key (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 combine them into a single comma-separated string.

Return the result table ordered by state and city in ascending order.

The result format is in the following example.



Example:

Input:

cities table:

+-------------+---------------+
| state       | city          |
+-------------+---------------+
| California  | Los Angeles   |
| California  | San Francisco |
| California  | San Diego     |
| Texas       | Houston       |
| Texas       | Austin        |
| Texas       | Dallas        |
| New York    | New York City |
| New York    | Buffalo       |
| New York    | Rochester     |
+-------------+---------------+
Output:

+-------------+---------------------------------------+
| state       | cities                                |
+-------------+---------------------------------------+
| California  | Los Angeles, San Diego, San Francisco |
| New York    | Buffalo, New York City, Rochester     |
| Texas       | Austin, Dallas, Houston               |
+-------------+---------------------------------------+
Explanation:

California: All cities ("Los Angeles", "San Diego", "San Francisco") are listed in a comma-separated string.
New York: All cities ("Buffalo", "New York City", "Rochester") are listed in a comma-separated string.
Texas: All cities ("Austin", "Dallas", "Houston") are listed in a comma-separated string.
Note: The output table is ordered by the state name in ascending order.
  1. # Write your MySQL query statement below
  2. SELECT
  3.     state,
  4.     GROUP_CONCAT(city ORDER BY city SEPARATOR ', ') AS cities
  5. FROM cities
  6. GROUP BY state
  7. ORDER BY state ASC;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-23 12:31:05 | 只看该作者
全局:
3204. Bitwise User Permissions Analysis
Medium
Topics
SQL Schema
Pandas Schema
Table: user_permissions

+--------------------------------------------------+--------------------------------------------------+
| Column Name | Type |
+--------------------------------------------------+--------------------------------------------------+
| user_id | int |
| permissions | int |
+--------------------------------------------------+--------------------------------------------------+
user_id is the primary key.
Each row of this table contains the user ID and their permissions encoded as an integer.
Consider that each bit in the permissions integer represents a different access level or feature that a user has.

Write a solution to calculate the following:

common_perms: The access level granted to all users. This is computed using a bitwise AND operation on the permissions column.
any_perms: The access level granted to any user. This is computed using a bitwise OR operation on the permissions column.
Return the result table in any order.

The result format is shown in the following example.

Example:

Input:

user_permissions table:

+--------------------------------------------------+--------------------------------------------------+
| user_id | permissions |
+--------------------------------------------------+--------------------------------------------------+
| 1 | 5 |
| 2 | 12 |
| 3 | 7 |
| 4 | 3 |
+--------------------------------------------------+--------------------------------------------------+

Output:

+--------------------------------------------------+--------------------------------------------------+
| common_perms | any_perms |
+--------------------------------------------------+--------------------------------------------------+
| 0 | 15 |
+--------------------------------------------------+--------------------------------------------------+

Explanation:

common_perms: Represents the bitwise AND result of all permissions:
For user 1 (5): 5 (binary 0101)
For user 2 (12): 12 (binary 1100)
For user 3 (7): 7 (binary 0111)
For user 4 (3): 3 (binary 0011)
Bitwise AND: 5 & 12 & 7 & 3 = 0 (binary 0000)
any_perms: Represents the bitwise OR result of all permissions:
Bitwise OR: 5 | 12 | 7 | 3 = 15 (binary 1111)
  1. # Write your MySQL query statement below
  2. SELECT
  3.     BIT_AND(permissions) AS common_perms,
  4.     BIT_OR(permissions) AS any_perms
  5. FROM user_permissions;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-23 12:32:18 | 只看该作者
全局:
3214. Year on Year Growth Rate
Hard
Topics
conpanies icon
Companies
SQL Schema
Pandas Schema
Table: user_transactions

+------------------+----------+
| Column Name      | Type     |
+------------------+----------+
| transaction_id   | integer  |
| product_id       | integer  |
| spend            | decimal  |
| transaction_date | datetime |
+------------------+----------+
The transaction_id column uniquely identifies each row in this table.
Each row of this table contains the transaction ID, product ID, the spend amount, and the transaction date.
Write a solution to calculate the year-on-year growth rate for the total spend for each product.

The result table should include the following columns:

year: The year of the transaction.
product_id: The ID of the product.
curr_year_spend: The total spend for the current year.
prev_year_spend: The total spend for the previous year.
yoy_rate: The year-on-year growth rate percentage, rounded to 2 decimal places.
Return the result table ordered by product_id,year in ascending order.

The result format is in the following example.



Example:

Input:

user_transactions table:

+----------------+------------+---------+---------------------+
| transaction_id | product_id | spend   | transaction_date    |
+----------------+------------+---------+---------------------+
| 1341           | 123424     | 1500.60 | 2019-12-31 12:00:00 |
| 1423           | 123424     | 1000.20 | 2020-12-31 12:00:00 |
| 1623           | 123424     | 1246.44 | 2021-12-31 12:00:00 |
| 1322           | 123424     | 2145.32 | 2022-12-31 12:00:00 |
+----------------+------------+---------+---------------------+
Output:

+------+------------+----------------+----------------+----------+
| year | product_id | curr_year_spend| prev_year_spend| yoy_rate |
+------+------------+----------------+----------------+----------+
| 2019 | 123424     | 1500.60        | NULL           | NULL     |
| 2020 | 123424     | 1000.20        | 1500.60        | -33.35   |
| 2021 | 123424     | 1246.44        | 1000.20        | 24.62    |
| 2022 | 123424     | 2145.32        | 1246.44        | 72.12    |
+------+------------+----------------+----------------+----------+
Explanation:

For product ID 123424:
In 2019:
Current year's spend is 1500.60
No previous year's spend recorded
YoY growth rate: NULL
In 2020:
Current year's spend is 1000.20
Previous year's spend is 1500.60
YoY growth rate: ((1000.20 - 1500.60) / 1500.60) * 100 = -33.35%
In 2021:
Current year's spend is 1246.44
Previous year's spend is 1000.20
YoY growth rate: ((1246.44 - 1000.20) / 1000.20) * 100 = 24.62%
In 2022:
Current year's spend is 2145.32
Previous year's spend is 1246.44
YoY growth rate: ((2145.32 - 1246.44) / 1246.44) * 100 = 72.12%
Note: Output table is ordered by product_id and year in ascending order.
  1. # Write your MySQL query statement below
  2. WITH yearly_spend AS (
  3.     SELECT
  4.         YEAR(transaction_date) AS year,
  5.         product_id,
  6.         SUM(spend) AS curr_year_spend
  7.     FROM user_transactions
  8.     GROUP BY YEAR(transaction_date), product_id
  9. ),
  10. spend_with_prev AS (
  11.     SELECT
  12.         year,
  13.         product_id,
  14.         curr_year_spend,
  15.         LAG(curr_year_spend) OVER (
  16.             PARTITION BY product_id
  17.             ORDER BY year
  18.         ) AS prev_year_spend
  19.     FROM yearly_spend
  20. )
  21. SELECT
  22.     year,
  23.     product_id,
  24.     curr_year_spend,
  25.     prev_year_spend,
  26.     ROUND(
  27.         (curr_year_spend - prev_year_spend)
  28.         / NULLIF(prev_year_spend, 0) * 100,
  29.         2
  30.     ) AS yoy_rate
  31. FROM spend_with_prev
  32. ORDER BY product_id, year;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-23 12:35:22 | 只看该作者
全局:
3220. Odd and Even Transactions
Medium
Topics
SQL Schema
Pandas Schema
Table: transactions

+------------------+------+
| Column Name      | Type |
+------------------+------+
| transaction_id   | int  |
| amount           | int  |
| transaction_date | date |
+------------------+------+
The transactions_id column uniquely identifies each row in this table.
Each row of this table contains the transaction id, amount and transaction date.
Write a solution to find the sum of amounts for odd and even transactions for each day. If there are no odd or even transactions for a specific date, display as 0.

Return the result table ordered by transaction_date in ascending order.

The result format is in the following example.



Example:

Input:

transactions table:

+----------------+--------+------------------+
| transaction_id | amount | transaction_date |
+----------------+--------+------------------+
| 1              | 150    | 2024-07-01       |
| 2              | 200    | 2024-07-01       |
| 3              | 75     | 2024-07-01       |
| 4              | 300    | 2024-07-02       |
| 5              | 50     | 2024-07-02       |
| 6              | 120    | 2024-07-03       |
+----------------+--------+------------------+
  
Output:

+------------------+---------+----------+
| transaction_date | odd_sum | even_sum |
+------------------+---------+----------+
| 2024-07-01       | 75      | 350      |
| 2024-07-02       | 0       | 350      |
| 2024-07-03       | 0       | 120      |
+------------------+---------+----------+
  
Explanation:

For transaction dates:
2024-07-01:
Sum of amounts for odd transactions: 75
Sum of amounts for even transactions: 150 + 200 = 350
2024-07-02:
Sum of amounts for odd transactions: 0
Sum of amounts for even transactions: 300 + 50 = 350
2024-07-03:
Sum of amounts for odd transactions: 0
Sum of amounts for even transactions: 120
Note: The output table is ordered by transaction_date in ascending order.
  1. import pandas as pd

  2. def sum_daily_odd_even(transactions: pd.DataFrame) -> pd.DataFrame:

  3.     # 复制一份避免修改原 DataFrame(面试中好习惯)
  4.     df = transactions.copy()

  5.     # 判断 amount 是否为奇数(用 != 0 比 == 1 更稳妥,避免负数取模细节)
  6.     is_odd = df["amount"] % 2 != 0

  7.     df["odd_sum"] = df["amount"].where(is_odd, 0)
  8.     df["even_sum"] = df["amount"].where(~is_odd, 0)

  9.     result = (
  10.         df.groupby("transaction_date", as_index=False)[["odd_sum", "even_sum"]]
  11.         .sum()
  12.         .sort_values("transaction_date", ascending=True)
  13.     )

  14.     return result
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-23 12:36:21 | 只看该作者
全局:
3230. Customer Purchasing Behavior Analysis
Medium
Topics
SQL Schema
Pandas Schema
Table: Transactions

+------------------+---------+
| Column Name      | Type    |
+------------------+---------+
| transaction_id   | int     |
| customer_id      | int     |
| product_id       | int     |
| transaction_date | date    |
| amount           | decimal |
+------------------+---------+
transaction_id is the unique identifier for this table.
Each row of this table contains information about a transaction, including the customer ID, product ID, date, and amount spent.
Table: Products

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_id  | int     |
| category    | varchar |
| price       | decimal |
+-------------+---------+
product_id is the unique identifier for this table.
Each row of this table contains information about a product, including its category and price.
Write a solution to analyze customer purchasing behavior. For each customer, calculate:

The total amount spent.
The number of transactions.
The number of unique product categories purchased.
The average amount spent.
The most frequently purchased product category (if there is a tie, choose the one with the most recent transaction).
A loyalty score defined as: (Number of transactions * 10) + (Total amount spent / 100).
Round total_amount, avg_transaction_amount, and loyalty_score to 2 decimal places.

Return the result table ordered by loyalty_score in descending order, then by customer_id in ascending order.

The query result format is in the following example.



Example:

Input:

Transactions table:

+----------------+-------------+------------+------------------+--------+
| transaction_id | customer_id | product_id | transaction_date | amount |
+----------------+-------------+------------+------------------+--------+
| 1              | 101         | 1          | 2023-01-01       | 100.00 |
| 2              | 101         | 2          | 2023-01-15       | 150.00 |
| 3              | 102         | 1          | 2023-01-01       | 100.00 |
| 4              | 102         | 3          | 2023-01-22       | 200.00 |
| 5              | 101         | 3          | 2023-02-10       | 200.00 |
+----------------+-------------+------------+------------------+--------+
Products table:

+------------+----------+--------+
| product_id | category | price  |
+------------+----------+--------+
| 1          | A        | 100.00 |
| 2          | B        | 150.00 |
| 3          | C        | 200.00 |
+------------+----------+--------+
Output:

+-------------+--------------+-------------------+-------------------+------------------------+--------------+---------------+
| customer_id | total_amount | transaction_count | unique_categories | avg_transaction_amount | top_category | loyalty_score |
+-------------+--------------+-------------------+-------------------+------------------------+--------------+---------------+
| 101         | 450.00       | 3                 | 3                 | 150.00                 | C            | 34.50         |
| 102         | 300.00       | 2                 | 2                 | 150.00                 | C            | 23.00         |
+-------------+--------------+-------------------+-------------------+------------------------+--------------+---------------+
Explanation:

For customer 101:
Total amount spent: 100.00 + 150.00 + 200.00 = 450.00
Number of transactions: 3
Unique categories: A, B, C (3 categories)
Average transaction amount: 450.00 / 3 = 150.00
Top category: C (Customer 101 made 1 purchase each in categories A, B, and C. Since the count is the same for all categories, we choose the most recent transaction, which is category C on 2023-02-10)
Loyalty score: (3 * 10) + (450.00 / 100) = 34.50
For customer 102:
Total amount spent: 100.00 + 200.00 = 300.00
Number of transactions: 2
Unique categories: A, C (2 categories)
Average transaction amount: 300.00 / 2 = 150.00
Top category: C (Customer 102 made 1 purchase each in categories A and C. Since the count is the same for both categories, we choose the most recent transaction, which is category C on 2023-01-22)
Loyalty score: (2 * 10) + (300.00 / 100) = 23.00
Note: The output is ordered by loyalty_score in descending order, then by customer_id in ascending order.
  1. # Write your MySQL query statement below
  2. WITH CategoryStats AS (
  3.     SELECT
  4.         t.customer_id,
  5.         p.category,
  6.         COUNT(*) AS cat_count,
  7.         MAX(t.transaction_date) AS last_date,
  8.         ROW_NUMBER() OVER (
  9.             PARTITION BY t.customer_id
  10.             ORDER BY COUNT(*) DESC, MAX(t.transaction_date) DESC
  11.         ) AS rn
  12.     FROM Transactions t
  13.     JOIN Products p
  14.         ON t.product_id = p.product_id
  15.     GROUP BY t.customer_id, p.category
  16. ),
  17. CustomerSummary AS (
  18.     SELECT
  19.         t.customer_id,
  20.         ROUND(SUM(t.amount), 2) AS total_amount,
  21.         COUNT(*) AS transaction_count,
  22.         COUNT(DISTINCT p.category) AS unique_categories,
  23.         ROUND(AVG(t.amount), 2) AS avg_transaction_amount,
  24.         ROUND(COUNT(*) * 10 + SUM(t.amount) / 100, 2) AS loyalty_score
  25.     FROM Transactions t
  26.     JOIN Products p
  27.         ON t.product_id = p.product_id
  28.     GROUP BY t.customer_id
  29. )
  30. SELECT
  31.     cs.customer_id,
  32.     cs.total_amount,
  33.     cs.transaction_count,
  34.     cs.unique_categories,
  35.     cs.avg_transaction_amount,
  36.     cat.category AS top_category,
  37.     cs.loyalty_score
  38. FROM CustomerSummary cs
  39. JOIN CategoryStats cat
  40.     ON cs.customer_id = cat.customer_id
  41.    AND cat.rn = 1
  42. ORDER BY cs.loyalty_score DESC, cs.customer_id ASC;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-23 12:37:40 | 只看该作者
全局:
3236. CEO Subordinate Hierarchy
Hard
Topics
SQL Schema
Pandas Schema
Table: Employees

+---------------+---------+
| Column Name   | Type    |
+---------------+---------+
| employee_id   | int     |
| employee_name | varchar |
| manager_id    | int     |
| salary        | int     |
+---------------+---------+
employee_id is the unique identifier for this table.
manager_id is the employee_id of the employee's manager. The CEO has a NULL manager_id.
Write a solution to find subordinates of the CEO (both direct and indirect), along with their level in the hierarchy and their salary difference from the CEO.

The result should have the following columns:

The query result format is in the following example.

subordinate_id: The employee_id of the subordinate
subordinate_name: The name of the subordinate
hierarchy_level: The level of the subordinate in the hierarchy (1 for direct reports, 2 for their direct reports, and so on)
salary_difference: The difference between the subordinate's salary and the CEO's salary
Return the result table ordered by hierarchy_level ascending, and then by subordinate_id ascending.

The query result format is in the following example.



Example:

Input:

Employees table:

+-------------+----------------+------------+---------+
| employee_id | employee_name  | manager_id | salary  |
+-------------+----------------+------------+---------+
| 1           | Alice          | NULL       | 150000  |
| 2           | Bob            | 1          | 120000  |
| 3           | Charlie        | 1          | 110000  |
| 4           | David          | 2          | 105000  |
| 5           | Eve            | 2          | 100000  |
| 6           | Frank          | 3          | 95000   |
| 7           | Grace          | 3          | 98000   |
| 8           | Helen          | 5          | 90000   |
+-------------+----------------+------------+---------+
Output:

+----------------+------------------+------------------+-------------------+
| subordinate_id | subordinate_name | hierarchy_level  | salary_difference |
+----------------+------------------+------------------+-------------------+
| 2              | Bob              | 1                | -30000            |
| 3              | Charlie          | 1                | -40000            |
| 4              | David            | 2                | -45000            |
| 5              | Eve              | 2                | -50000            |
| 6              | Frank            | 2                | -55000            |
| 7              | Grace            | 2                | -52000            |
| 8              | Helen            | 3                | -60000            |
+----------------+------------------+------------------+-------------------+
Explanation:

Bob and Charlie are direct subordinates of Alice (CEO) and thus have a hierarchy_level of 1.
David and Eve report to Bob, while Frank and Grace report to Charlie, making them second-level subordinates (hierarchy_level 2).
Helen reports to Eve, making Helen a third-level subordinate (hierarchy_level 3).
Salary differences are calculated relative to Alice's salary of 150000.
The result is ordered by hierarchy_level ascending, and then by subordinate_id ascending.
Note: The output is ordered first by hierarchy_level in ascending order, then by subordinate_id in ascending order.
  1. # Write your MySQL query statement below
  2. WITH RECURSIVE CEO AS (
  3.     SELECT
  4.         employee_id AS ceo_id,
  5.         salary AS ceo_salary
  6.     FROM Employees
  7.     WHERE manager_id IS NULL
  8. ),
  9. SubordinateHierarchy AS (
  10.     -- 锚点查询:CEO 的直接下属(层级为 1)
  11.     SELECT
  12.         e.employee_id AS subordinate_id,
  13.         e.employee_name AS subordinate_name,
  14.         1 AS hierarchy_level,
  15.         e.salary - c.ceo_salary AS salary_difference
  16.     FROM Employees e
  17.     JOIN CEO c
  18.         ON e.manager_id = c.ceo_id

  19.     UNION ALL

  20.     -- 递归查询:下一级下属,层级 +1
  21.     SELECT
  22.         e.employee_id AS subordinate_id,
  23.         e.employee_name AS subordinate_name,
  24.         sh.hierarchy_level + 1 AS hierarchy_level,
  25.         e.salary - c.ceo_salary AS salary_difference
  26.     FROM Employees e
  27.     JOIN SubordinateHierarchy sh
  28.         ON e.manager_id = sh.subordinate_id
  29.     CROSS JOIN CEO c
  30. )
  31. SELECT
  32.     subordinate_id,
  33.     subordinate_name,
  34.     hierarchy_level,
  35.     salary_difference
  36. FROM SubordinateHierarchy
  37. ORDER BY hierarchy_level ASC, subordinate_id ASC;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-23 12:39:04 | 只看该作者
全局:
3246. Premier League Table Ranking
Easy
Topics
SQL Schema
Pandas Schema
Table: TeamStats

+------------------+---------+
| Column Name      | Type    |
+------------------+---------+
| team_id          | int     |
| team_name        | varchar |
| matches_played   | int     |
| wins             | int     |
| draws            | int     |
| losses           | int     |
+------------------+---------+
team_id is the unique key for this table.
This table contains team id, team name, matches_played, wins, draws, and losses.
Write a solution to calculate the points and rank for each team in the league. Points are calculated as follows:

3 points for a win
1 point for a draw
0 points for a loss
Note: Teams with the same points must be assigned the same rank.

Return the result table ordered by points in descending, and then by team_name in ascending order.

The query result format is in the following example.



Example:

Input:

TeamStats table:

+---------+-----------------+----------------+------+-------+--------+
| team_id | team_name       | matches_played | wins | draws | losses |
+---------+-----------------+----------------+------+-------+--------+
| 1       | Manchester City | 10             | 6    | 2     | 2      |
| 2       | Liverpool       | 10             | 6    | 2     | 2      |
| 3       | Chelsea         | 10             | 5    | 3     | 2      |
| 4       | Arsenal         | 10             | 4    | 4     | 2      |
| 5       | Tottenham       | 10             | 3    | 5     | 2      |
+---------+-----------------+----------------+------+-------+--------+
Output:

+---------+-----------------+--------+----------+
| team_id | team_name       | points | position |
+---------+-----------------+--------+----------+
| 2       | Liverpool       | 20     | 1        |
| 1       | Manchester City | 20     | 1        |
| 3       | Chelsea         | 18     | 3        |
| 4       | Arsenal         | 16     | 4        |
| 5       | Tottenham       | 14     | 5        |
+---------+-----------------+--------+----------+
Explanation:

Manchester City and Liverpool both have 20 points (6 wins * 3 points + 2 draws * 1 point), so they share position 1.
Chelsea has 18 points (5 wins * 3 points + 3 draws * 1 point) and is position 3rd.
Arsenal has 16 points (4 wins * 3 points + 4 draws * 1 point) and is position 4th.
Tottenham has 14 points (3 wins * 3 points + 5 draws * 1 point) and is position 5th.
The output table is ordered by points in descending order, then by team_name in ascending order.
  1. # Write your MySQL query statement below
  2. SELECT
  3.     team_id,
  4.     team_name,
  5.     wins * 3 + draws AS points,
  6.     RANK() OVER (ORDER BY wins * 3 + draws DESC) AS position
  7. FROM TeamStats
  8. ORDER BY points DESC, team_name ASC;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-23 12:39:47 | 只看该作者
全局:
3252. Premier League Table Ranking II
Medium
Topics
SQL Schema
Pandas Schema
Table: TeamStats

+------------------+---------+
| Column Name      | Type    |
+------------------+---------+
| team_id          | int     |
| team_name        | varchar |
| matches_played   | int     |
| wins             | int     |
| draws            | int     |
| losses           | int     |
+------------------+---------+
team_id is the unique key for this table.
This table contains team id, team name, matches_played, wins, draws, and losses.
Write a solution to calculate the points, position, and tier for each team in the league. Points are calculated as follows:

3 points for a win
1 point for a draw
0 points for a loss
Note: Teams with the same points must be assigned the same position.

Tier ranking:

Divide the league into 3 tiers based on points:
Tier 1: Top 33% of teams
Tier 2: Middle 33% of teams
Tier 3: Bottom 34% of teams
In case of ties at tier boundaries, place tied teams in the higher tier.
Return the result table ordered by points in descending, and then by team_name in ascending order.

The query result format is in the following example.



Example:

Input:

TeamStats table:

+---------+-------------------+----------------+------+-------+--------+
| team_id | team_name         | matches_played | wins | draws | losses |
+---------+-------------------+----------------+------+-------+--------+
| 1       | Chelsea           | 22             | 13   | 2     | 7      |
| 2       | Nottingham Forest | 27             | 6    | 6     | 15     |
| 3       | Liverpool         | 17             | 1    | 8     | 8      |
| 4       | Aston Villa       | 20             | 1    | 6     | 13     |
| 5       | Fulham            | 31             | 18   | 1     | 12     |
| 6       | Burnley           | 26             | 6    | 9     | 11     |
| 7       | Newcastle United  | 33             | 11   | 10    | 12     |
| 8       | Sheffield United  | 20             | 18   | 2     | 0      |
| 9       | Luton Town        | 5              | 4    | 0     | 1      |
| 10      | Everton           | 14             | 2    | 6     | 6      |
+---------+-------------------+----------------+------+-------+--------+
Output:

+-------------------+--------+----------+---------+
| team_name         | points | position | tier    |
+-------------------+--------+----------+---------+
| Sheffield United  | 56     | 1        | Tier 1  |
| Fulham            | 55     | 2        | Tier 1  |
| Newcastle United  | 43     | 3        | Tier 1  |
| Chelsea           | 41     | 4        | Tier 1  |
| Burnley           | 27     | 5        | Tier 2  |
| Nottingham Forest | 24     | 6        | Tier 2  |
| Everton           | 12     | 7        | Tier 2  |
| Luton Town        | 12     | 7        | Tier 2  |
| Liverpool         | 11     | 9        | Tier 3  |
| Aston Villa       | 9      | 10       | Tier 3  |
+-------------------+--------+----------+---------+
Explanation:

Sheffield United has 56 points (18 wins * 3 points + 2 draws * 1 point) and is in position 1.
Fulham has 55 points (18 wins * 3 points + 1 draw * 1 point) and is in position 2.
Newcastle United has 43 points (11 wins * 3 points + 10 draws * 1 point) and is in position 3.
Chelsea has 41 points (13 wins * 3 points + 2 draws * 1 point) and is in position 4.
Burnley has 27 points (6 wins * 3 points + 9 draws * 1 point) and is in position 5.
Nottingham Forest has 24 points (6 wins * 3 points + 6 draws * 1 point) and is in position 6.
Everton and Luton Town both have 12 points, with Everton having 2 wins * 3 points + 6 draws * 1 point, and Luton Town having 4 wins * 3 points. Both teams share position 7.
Liverpool has 11 points (1 win * 3 points + 8 draws * 1 point) and is in position 9.
Aston Villa has 9 points (1 win * 3 points + 6 draws * 1 point) and is in position 10.
Tier Calculation:

Tier 1: The top 33% of teams based on points. Sheffield United, Fulham, Newcastle United, and Chelsea fall into Tier 1.
Tier 2: The middle 33% of teams. Burnley, Nottingham Forest, Everton, and Luton Town fall into Tier 2.
Tier 3: The bottom 34% of teams. Liverpool and Aston Villa fall into Tier 3.
  1. # Write your MySQL query statement below
  2. WITH RankedTeams AS (
  3.     SELECT
  4.         team_name,
  5.         wins * 3 + draws AS points,
  6.         RANK() OVER (ORDER BY wins * 3 + draws DESC) AS position,
  7.         COUNT(*) OVER () AS total_teams
  8.     FROM TeamStats
  9. )
  10. SELECT
  11.     team_name,
  12.     points,
  13.     position,
  14.     CASE
  15.         WHEN position <= CEIL(total_teams / 3.0) THEN 'Tier 1'
  16.         WHEN position <= CEIL(2 * total_teams / 3.0) THEN 'Tier 2'
  17.         ELSE 'Tier 3'
  18.     END AS tier
  19. FROM RankedTeams
  20. ORDER BY points DESC, team_name ASC;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3262. Find Overlapping Shifts
Medium
Topics
SQL Schema
Pandas Schema
Table: EmployeeShifts

+------------------+---------+
| Column Name      | Type    |
+------------------+---------+
| employee_id      | int     |
| start_time       | time    |
| end_time         | time    |
+------------------+---------+
(employee_id, start_time) is the unique key for this table.
This table contains information about the shifts worked by employees, including the start and end times on a specific date.
Write a solution to count the number of overlapping shifts for each employee. Two shifts are considered overlapping if one shift’s end_time is later than another shift’s start_time.

Return the result table ordered by employee_id in ascending order.

The query result format is in the following example.



Example:

Input:

EmployeeShifts table:

+-------------+------------+----------+
| employee_id | start_time | end_time |
+-------------+------------+----------+
| 1           | 08:00:00   | 12:00:00 |
| 1           | 11:00:00   | 15:00:00 |
| 1           | 14:00:00   | 18:00:00 |
| 2           | 09:00:00   | 17:00:00 |
| 2           | 16:00:00   | 20:00:00 |
| 3           | 10:00:00   | 12:00:00 |
| 3           | 13:00:00   | 15:00:00 |
| 3           | 16:00:00   | 18:00:00 |
| 4           | 08:00:00   | 10:00:00 |
| 4           | 09:00:00   | 11:00:00 |
+-------------+------------+----------+
Output:

+-------------+--------------------+
| employee_id | overlapping_shifts |
+-------------+--------------------+
| 1           | 2                  |
| 2           | 1                  |
| 4           | 1                  |
+-------------+--------------------+
Explanation:

Employee 1 has 3 shifts:
08:00:00 to 12:00:00
11:00:00 to 15:00:00
14:00:00 to 18:00:00
The first shift overlaps with the second, and the second overlaps with the third, resulting in 2 overlapping shifts.
Employee 2 has 2 shifts:
09:00:00 to 17:00:00
16:00:00 to 20:00:00
These shifts overlap with each other, resulting in 1 overlapping shift.
Employee 3 has 3 shifts:
10:00:00 to 12:00:00
13:00:00 to 15:00:00
16:00:00 to 18:00:00
None of these shifts overlap, so Employee 3 is not included in the output.
Employee 4 has 2 shifts:
08:00:00 to 10:00:00
09:00:00 to 11:00:00
These shifts overlap with each other, resulting in 1 overlapping shift.
The output shows the employee_id and the count of overlapping shifts for each employee who has at least one overlapping shift, ordered by employee_id in ascending order.
  1. # Write your MySQL query statement below
  2. SELECT
  3.     a.employee_id,
  4.     COUNT(*) AS overlapping_shifts
  5. FROM EmployeeShifts a
  6. JOIN EmployeeShifts b
  7.   ON a.employee_id = b.employee_id
  8. AND a.start_time < b.start_time
  9. AND a.end_time   > b.start_time
  10. GROUP BY a.employee_id
  11. ORDER BY a.employee_id;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 3 天前 | 只看该作者
全局:
3268. Find Overlapping Shifts II
Hard
Topics
SQL Schema
Pandas Schema
Table: EmployeeShifts

+------------------+----------+
| Column Name      | Type     |
+------------------+----------+
| employee_id      | int      |
| start_time       | datetime |
| end_time         | datetime |
+------------------+----------+
(employee_id, start_time) is the unique key for this table.
This table contains information about the shifts worked by employees, including the start time, and end time.
Write a solution to analyze overlapping shifts for each employee. Two shifts are considered overlapping if they occur on the same date and one shift's end_time is later than another shift's start_time.

For each employee, calculate the following:

The maximum number of shifts that overlap at any given time.
The total duration of all overlaps in minutes.
Return the result table ordered by employee_id in ascending order.

The query result format is in the following example.



Example:

Input:

EmployeeShifts table:

+-------------+---------------------+---------------------+
| employee_id | start_time          | end_time            |
+-------------+---------------------+---------------------+
| 1           | 2023-10-01 09:00:00 | 2023-10-01 17:00:00 |
| 1           | 2023-10-01 15:00:00 | 2023-10-01 23:00:00 |
| 1           | 2023-10-01 16:00:00 | 2023-10-02 00:00:00 |
| 2           | 2023-10-01 09:00:00 | 2023-10-01 17:00:00 |
| 2           | 2023-10-01 11:00:00 | 2023-10-01 19:00:00 |
| 3           | 2023-10-01 09:00:00 | 2023-10-01 17:00:00 |
+-------------+---------------------+---------------------+
Output:

+-------------+---------------------------+------------------------+
| employee_id | max_overlapping_shifts    | total_overlap_duration |
+-------------+---------------------------+------------------------+
| 1           | 3                         | 600                    |
| 2           | 2                         | 360                    |
| 3           | 1                         | 0                      |
+-------------+---------------------------+------------------------+
Explanation:

Employee 1 has 3 shifts:
2023-10-01 09:00:00 to 2023-10-01 17:00:00
2023-10-01 15:00:00 to 2023-10-01 23:00:00
2023-10-01 16:00:00 to 2023-10-02 00:00:00
The maximum number of overlapping shifts is 3 (from 16:00 to 17:00). The total overlap duration is: - 2 hours (15:00-17:00) between 1st and 2nd shifts - 1 hour (16:00-17:00) between 1st and 3rd shifts - 7 hours (16:00-23:00) between 2nd and 3rd shifts Total: 10 hours = 600 minutes
Employee 2 has 2 shifts:
2023-10-01 09:00:00 to 2023-10-01 17:00:00
2023-10-01 11:00:00 to 2023-10-01 19:00:00
The maximum number of overlapping shifts is 2. The total overlap duration is 6 hours (11:00-17:00) = 360 minutes.
Employee 3 has only 1 shift, so there are no overlaps.
The output table contains the employee_id, the maximum number of simultaneous overlaps, and the total overlap duration in minutes for each employee, ordered by employee_id in ascending order.

  1. # Write your MySQL query statement below
  2. WITH events AS (
  3.     SELECT employee_id, start_time AS t,  1 AS delta FROM EmployeeShifts
  4.     UNION ALL
  5.     SELECT employee_id, end_time   AS t, -1 AS delta FROM EmployeeShifts
  6. ),
  7. running AS (
  8.     SELECT
  9.         employee_id,
  10.         SUM(delta) OVER (
  11.             PARTITION BY employee_id
  12.             ORDER BY t, delta
  13.             ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
  14.         ) AS cnt
  15.     FROM events
  16. ),
  17. max_overlap AS (
  18.     SELECT employee_id, MAX(cnt) AS max_overlapping_shifts
  19.     FROM running
  20.     GROUP BY employee_id
  21. ),
  22. overlap_minutes AS (
  23.     SELECT
  24.         a.employee_id,
  25.         SUM(TIMESTAMPDIFF(MINUTE, b.start_time, LEAST(a.end_time, b.end_time))) AS total_overlap_duration
  26.     FROM EmployeeShifts a
  27.     JOIN EmployeeShifts b
  28.       ON a.employee_id = b.employee_id
  29.      AND a.start_time < b.start_time
  30.      AND a.end_time   > b.start_time
  31.     GROUP BY a.employee_id
  32. )
  33. SELECT
  34.     m.employee_id,
  35.     m.max_overlapping_shifts,
  36.     COALESCE(o.total_overlap_duration, 0) AS total_overlap_duration
  37. FROM max_overlap m
  38. LEFT JOIN overlap_minutes o USING (employee_id)
  39. ORDER BY m.employee_id;

复制代码
回复

使用道具 举报

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

本版积分规则

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