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

刷题记录帖子

🔗
 楼主| Myron2017 2026-11-21 13:13:32 | 只看该作者
全局:
2298. Tasks Count in the Weekend
Medium
Topics
SQL Schema
Pandas Schema
Table: Tasks

+-------------+------+
| Column Name | Type |
+-------------+------+
| task_id     | int  |
| assignee_id | int  |
| submit_date | date |
+-------------+------+
task_id is the primary key (column with unique values) for this table.
Each row in this table contains the ID of a task, the id of the assignee, and the submission date.


Write a solution to report:

the number of tasks that were submitted during the weekend (Saturday, Sunday) as weekend_cnt, and
the number of tasks that were submitted during the working days as working_cnt.
Return the result table in any order.

The result format is shown in the following example.



Example 1:

Input:
Tasks table:
+---------+-------------+-------------+
| task_id | assignee_id | submit_date |
+---------+-------------+-------------+
| 1       | 1           | 2022-06-13  |
| 2       | 6           | 2022-06-14  |
| 3       | 6           | 2022-06-15  |
| 4       | 3           | 2022-06-18  |
| 5       | 5           | 2022-06-19  |
| 6       | 7           | 2022-06-19  |
+---------+-------------+-------------+
Output:
+-------------+-------------+
| weekend_cnt | working_cnt |
+-------------+-------------+
| 3           | 3           |
+-------------+-------------+
Explanation:
Task 1 was submitted on Monday.
Task 2 was submitted on Tuesday.
Task 3 was submitted on Wednesday.
Task 4 was submitted on Saturday.
Task 5 was submitted on Sunday.
Task 6 was submitted on Sunday.
3 tasks were submitted during the weekend.
3 tasks were submitted during the working days.
  1. SELECT
  2.     SUM(CASE
  3.         WHEN DAYOFWEEK(submit_date) IN (1, 7) THEN 1
  4.         ELSE 0
  5.     END) AS weekend_cnt,
  6.     SUM(CASE
  7.         WHEN DAYOFWEEK(submit_date) BETWEEN 2 AND 6 THEN 1
  8.         ELSE 0
  9.     END) AS working_cnt
  10. FROM Tasks;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-21 13:14:18 | 只看该作者
全局:
2292. Products With Three or More Orders in Two Consecutive Years
Medium
Topics
SQL Schema
Pandas Schema
Table: Orders

+---------------+------+
| Column Name   | Type |
+---------------+------+
| order_id      | int  |
| product_id    | int  |
| quantity      | int  |
| purchase_date | date |
+---------------+------+
order_id contains unique values.
Each row in this table contains the ID of an order, the id of the product purchased, the quantity, and the purchase date.


Write a solution to report the IDs of all the products that were ordered three or more times in two consecutive years.

Return the result table in any order.

The result format is shown in the following example.



Example 1:

Input:
Orders table:
+----------+------------+----------+---------------+
| order_id | product_id | quantity | purchase_date |
+----------+------------+----------+---------------+
| 1        | 1          | 7        | 2020-03-16    |
| 2        | 1          | 4        | 2020-12-02    |
| 3        | 1          | 7        | 2020-05-10    |
| 4        | 1          | 6        | 2021-12-23    |
| 5        | 1          | 5        | 2021-05-21    |
| 6        | 1          | 6        | 2021-10-11    |
| 7        | 2          | 6        | 2022-10-11    |
+----------+------------+----------+---------------+
Output:
+------------+
| product_id |
+------------+
| 1          |
+------------+
Explanation:
Product 1 was ordered in 2020 three times and in 2021 three times. Since it was ordered three times in two consecutive years, we include it in the answer.
Product 2 was ordered one time in 2022. We do not include it in the answer.
  1. # Write your MySQL query statement below
  2. SELECT DISTINCT a.product_id
  3. FROM Orders a
  4. JOIN Orders b
  5.     ON a.product_id = b.product_id
  6.     AND YEAR(b.purchase_date) = YEAR(a.purchase_date) + 1
  7. GROUP BY a.product_id, YEAR(a.purchase_date)
  8. HAVING COUNT(DISTINCT a.order_id) >= 3
  9.    AND COUNT(DISTINCT b.order_id) >= 3;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-22 11:02:42 | 只看该作者
全局:
2253. Dynamic Unpivoting of a Table
Attempted
Hard
Topics
SQL Schema
0
Table: Products

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| product_id  | int     |
| store_name1 | int     |
| store_name2 | int     |
|      :      | int     |
|      :      | int     |
|      :      | int     |
| store_namen | int     |
+-------------+---------+
product_id is the primary key for this table.
Each row in this table indicates the product's price in n different stores.
If the product is not available in a store, the price will be null in that store's column.
The names of the stores may change from one testcase to another. There will be at least 1 store and at most 30 stores.


Important note: This problem targets those who have a good experience with SQL. If you are a beginner, we recommend that you skip it for now.

Implement the procedure UnpivotProducts to reorganize the Products table so that each row has the id of one product, the name of a store where it is sold, and its price in that store. If a product is not available in a store, do not include a row with that product_id and store combination in the result table. There should be three columns: product_id, store, and price.

The procedure should return the table after reorganizing it.

Return the result table in any order.

The query result format is in the following example.



Example 1:

Input:
Products table:
+------------+----------+--------+------+------+
| product_id | LC_Store | Nozama | Shop | Souq |
+------------+----------+--------+------+------+
| 1          | 100      | null   | 110  | null |
| 2          | null     | 200    | null | 190  |
| 3          | null     | null   | 1000 | 1900 |
+------------+----------+--------+------+------+
Output:
+------------+----------+-------+
| product_id | store    | price |
+------------+----------+-------+
| 1          | LC_Store | 100   |
| 1          | Shop     | 110   |
| 2          | Nozama   | 200   |
| 2          | Souq     | 190   |
| 3          | Shop     | 1000  |
| 3          | Souq     | 1900  |
+------------+----------+-------+
Explanation:
Product 1 is sold in LC_Store and Shop with prices of 100 and 110 respectively.
Product 2 is sold in Nozama and Souq with prices of 200 and 190.
Product 3 is sold in Shop and Souq with prices of 1000 and 1900.

2253. 动态逆透视(Unpivot)中文讲解
题目在做什么

Products 表是宽表:每个商店一列,单元格里是价格。题目要把它转成长表,每行只有 product_id、store、price 三列,价格为 NULL(该商店不卖)的组合不输出。

难点是商店列的名字和数量每个测试用例都不一样(1 到 30 个)。所以不能把列名写死,必须根据表结构动态生成 SQL。

如果列名固定,怎么写

固定为 LC_Store、Nozama、Shop、Souq 时,写法是每列一个 SELECT,再用 UNION ALL 拼起来:

sql
SELECT product_id, 'LC_Store' AS store, LC_Store AS price FROM Products WHERE LC_Store IS NOT NULL
UNION ALL
SELECT product_id, 'Nozama' AS store, Nozama AS price FROM Products WHERE Nozama IS NOT NULL
UNION ALL
...

动态版本做的事就是让 MySQL 自己生成这段文字,再执行它。

解法分三步
第一步:取出所有商店列名
sql
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = DATABASE()
  AND TABLE_NAME = 'Products'
  AND COLUMN_NAME <> 'product_id'

INFORMATION_SCHEMA.COLUMNS 是 MySQL 的元数据表,记录了每张表有哪些列。

TABLE_SCHEMA = DATABASE():限定在当前数据库,避免误取到其他库里的同名表。
COLUMN_NAME <> 'product_id':去掉 product_id,剩下的都是商店列。
第二步:为每个商店列拼一条 SELECT,再合并成一整句
sql
CONCAT('SELECT product_id, ''', COLUMN_NAME, ''' AS store, `',
       COLUMN_NAME, '` AS price FROM Products WHERE `',
       COLUMN_NAME, '` IS NOT NULL')

对列名 Shop,它会生成:

sql
SELECT product_id, 'Shop' AS store, `Shop` AS price FROM Products WHERE `Shop` IS NOT NULL

几个细节:

''' 是在字符串里写一个单引号(单引号要用两个单引号转义)。所以 'Shop' 作为字符串常量出现在 store 列。
反引号 ` 包住列名,防止列名带特殊字符或与关键字冲突。
WHERE ... IS NOT NULL 实现了"不卖就不输出"。

然后用 GROUP_CONCAT(... SEPARATOR ' UNION ALL ') 把每个商店对应的 SELECT 连成一个长字符串,存进用户变量 @sql。

第三步:执行生成的 SQL
sql
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
PREPARE:把字符串编译成预处理语句。
EXECUTE:执行,结果集就是存储过程的返回值。
DEALLOCATE PREPARE:释放资源。
为什么要加 SET SESSION group_concat_max_len = 1000000

GROUP_CONCAT 默认最多只保留 1024 个字符。每个商店的 SELECT 大约 100 个字符,30 个商店就是 3000 多字符,会被悄悄截断,生成的 SQL 就不完整,执行时报语法错误。所以必须先调大这个上限。

为什么用 UNION ALL 而不是 UNION

UNION 会去重,多一步额外开销。这里不同商店的行 store 值不同,本来就不会重复,所以用 UNION ALL 更快。
  1. CREATE PROCEDURE UnpivotProducts()
  2. BEGIN
  3.     SET SESSION group_concat_max_len = 1000000;

  4.     SELECT GROUP_CONCAT(
  5.                CONCAT('SELECT product_id, ''', COLUMN_NAME, ''' AS store, `',
  6.                       COLUMN_NAME, '` AS price FROM Products WHERE `',
  7.                       COLUMN_NAME, '` IS NOT NULL')
  8.                SEPARATOR ' UNION ALL ')
  9.     INTO @sql
  10.     FROM INFORMATION_SCHEMA.COLUMNS
  11.     WHERE TABLE_SCHEMA = DATABASE()
  12.       AND TABLE_NAME = 'Products'
  13.       AND COLUMN_NAME <> 'product_id';

  14.     PREPARE stmt FROM @sql;
  15.     EXECUTE stmt;
  16.     DEALLOCATE PREPARE stmt;
  17. END
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-22 11:09:02 | 只看该作者
全局:
2308. Arrange Table by Gender
Medium
Topics
SQL Schema
Pandas Schema
Table: Genders

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| user_id     | int     |
| gender      | varchar |
+-------------+---------+
user_id is the primary key (column with unique values) for this table.
gender is ENUM (category) of type 'female', 'male', or 'other'.
Each row in this table contains the ID of a user and their gender.
The table has an equal number of 'female', 'male', and 'other'.


Write a solution to rearrange the Genders table such that the rows alternate between 'female', 'other', and 'male' in order. The table should be rearranged such that the IDs of each gender are sorted in ascending order.

Return the result table in the mentioned order.

The result format is shown in the following example.



Example 1:

Input:
Genders table:
+---------+--------+
| user_id | gender |
+---------+--------+
| 4       | male   |
| 7       | female |
| 2       | other  |
| 5       | male   |
| 3       | female |
| 8       | male   |
| 6       | other  |
| 1       | other  |
| 9       | female |
+---------+--------+
Output:
+---------+--------+
| user_id | gender |
+---------+--------+
| 3       | female |
| 1       | other  |
| 4       | male   |
| 7       | female |
| 2       | other  |
| 5       | male   |
| 9       | female |
| 6       | other  |
| 8       | male   |
+---------+--------+
Explanation:
Female gender: IDs 3, 7, and 9.
Other gender: IDs 1, 2, and 6.
Male gender: IDs 4, 5, and 8.
We arrange the table alternating between 'female', 'other', and 'male'.
Note that the IDs of each gender are sorted in ascending order.

输出要按 female → other → male 循环交替,且每种性别内部按 user_id 升序。可以把它看成"发牌":每种性别各自排好队,然后每轮从三队里依次各取一个。

组内编号: ROW_NUMBER() OVER (PARTITION BY gender ORDER BY user_id) 给每种性别内部按 user_id 升序编号 rn(1, 2, 3, ...)。
轮次排序: 先按 rn 排序,同一轮的行排在一起。
轮内顺序: 同一个 rn 下,按 female, other, male 排。FIELD(gender, 'female', 'other', 'male') 返回该值在列表里的位置(1、2、3),所以可以直接当排序键。

题目保证三种性别数量相同,所以每一轮都恰好有三行,不会出现某一队提前用完的情况。
  1. # Write your MySQL query statement below
  2. SELECT user_id, gender
  3. FROM (
  4.     SELECT user_id,
  5.            gender,
  6.            ROW_NUMBER() OVER (PARTITION BY gender ORDER BY user_id) AS rn
  7.     FROM Genders
  8. ) t
  9. ORDER BY rn,
  10.          FIELD(gender, 'female', 'other', 'male');
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-22 11:09:51 | 只看该作者
全局:
2314. The First Day of the Maximum Recorded Degree in Each City
Medium
Topics
SQL Schema
Pandas Schema
Table: Weather

+-------------+------+
| Column Name | Type |
+-------------+------+
| city_id     | int  |
| day         | date |
| degree      | int  |
+-------------+------+
(city_id, day) is the primary key (combination of columns with unique values) for this table.
Each row in this table contains the degree of the weather of a city on a certain day.
All the degrees are recorded in the year 2022.


Write a solution to report the day that has the maximum recorded degree in each city. If the maximum degree was recorded for the same city multiple times, return the earliest day among them.

Return the result table ordered by city_id in ascending order.

The result format is shown in the following example.



Example 1:

Input:
Weather table:
+---------+------------+--------+
| city_id | day        | degree |
+---------+------------+--------+
| 1       | 2022-01-07 | -12    |
| 1       | 2022-03-07 | 5      |
| 1       | 2022-07-07 | 24     |
| 2       | 2022-08-07 | 37     |
| 2       | 2022-08-17 | 37     |
| 3       | 2022-02-07 | -7     |
| 3       | 2022-12-07 | -6     |
+---------+------------+--------+
Output:
+---------+------------+--------+
| city_id | day        | degree |
+---------+------------+--------+
| 1       | 2022-07-07 | 24     |
| 2       | 2022-08-07 | 37     |
| 3       | 2022-12-07 | -6     |
+---------+------------+--------+
Explanation:
For city 1, the maximum degree was recorded on 2022-07-07 with 24 degrees.
For city 2, the maximum degree was recorded on 2022-08-07 and 2022-08-17 with 37 degrees. We choose the earlier date (2022-08-07).
For city 3, the maximum degree was recorded on 2022-12-07 with -6 degrees.
  1. # Write your MySQL query statement below
  2. SELECT city_id, day, degree
  3. FROM (
  4.     SELECT city_id,
  5.            day,
  6.            degree,
  7.            ROW_NUMBER() OVER (PARTITION BY city_id ORDER BY degree DESC, day ASC) AS rn
  8.     FROM Weather
  9. ) t
  10. WHERE rn = 1
  11. ORDER BY city_id;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-22 11:18:35 | 只看该作者
全局:
2324. Product Sales Analysis IV
Solved
Medium
Topics
SQL Schema
Pandas Schema
Table: Sales

+-------------+-------+
| Column Name | Type  |
+-------------+-------+
| sale_id     | int   |
| product_id  | int   |
| user_id     | int   |
| quantity    | int   |
+-------------+-------+
sale_id contains unique values.
product_id is a foreign key (reference column) to Product table.
Each row of this table shows the ID of the product and the quantity purchased by a user.


Table: Product

+-------------+------+
| Column Name | Type |
+-------------+------+
| product_id  | int  |
| price       | int  |
+-------------+------+
product_id contains unique values.
Each row of this table indicates the price of each product.


Write a solution that reports for each user the product id on which the user spent the most money. In case the same user spent the most money on two or more products, report all of them.

Return the resulting table in any order.

The result format is in the following example.



Example 1:

Input:
Sales table:
+---------+------------+---------+----------+
| sale_id | product_id | user_id | quantity |
+---------+------------+---------+----------+
| 1       | 1          | 101     | 10       |
| 2       | 3          | 101     | 7        |
| 3       | 1          | 102     | 9        |
| 4       | 2          | 102     | 6        |
| 5       | 3          | 102     | 10       |
| 6       | 1          | 102     | 6        |
+---------+------------+---------+----------+
Product table:
+------------+-------+
| product_id | price |
+------------+-------+
| 1          | 10    |
| 2          | 25    |
| 3          | 15    |
+------------+-------+
Output:
+---------+------------+
| user_id | product_id |
+---------+------------+
| 101     | 3          |
| 102     | 1          |
| 102     | 2          |
| 102     | 3          |
+---------+------------+
Explanation:
User 101:
    - Spent 10 * 10 = 100 on product 1.
    - Spent 7 * 15 = 105 on product 3.
User 101 spent the most money on product 3.
User 102:
    - Spent (9 + 6) * 10 = 150 on product 1.
    - Spent 6 * 25 = 150 on product 2.
    - Spent 10 * 15 = 150 on product 3.
User 102 spent the most money on products 1, 2, and 3.
  1. # Write your MySQL query statement below
  2. SELECT user_id, product_id
  3. FROM (
  4.     SELECT s.user_id,
  5.            s.product_id,
  6.            RANK() OVER (
  7.                PARTITION BY s.user_id
  8.                ORDER BY SUM(s.quantity * p.price) DESC
  9.            ) AS rnk
  10.     FROM Sales s
  11.     JOIN Product p
  12.       ON s.product_id = p.product_id
  13.     GROUP BY s.user_id, s.product_id
  14. ) t
  15. WHERE rnk = 1;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-22 11:19:10 | 只看该作者
全局:
2329. Product Sales Analysis V
Easy
Topics
SQL Schema
Pandas Schema
Table: Sales

+-------------+-------+
| Column Name | Type  |
+-------------+-------+
| sale_id     | int   |
| product_id  | int   |
| user_id     | int   |
| quantity    | int   |
+-------------+-------+
sale_id contains unique values.
product_id is a foreign key (column with unique values) to Product table.
Each row of this table shows the ID of the product and the quantity purchased by a user.


Table: Product

+-------------+------+
| Column Name | Type |
+-------------+------+
| product_id  | int  |
| price       | int  |
+-------------+------+
product_id contains unique values.
Each row of this table indicates the price of each product.


Write a solution to report the spending of each user.

Return the resulting table ordered by spending in descending order. In case of a tie, order them by user_id in ascending order.

The result format is in the following example.



Example 1:

Input:
Sales table:
+---------+------------+---------+----------+
| sale_id | product_id | user_id | quantity |
+---------+------------+---------+----------+
| 1       | 1          | 101     | 10       |
| 2       | 2          | 101     | 1        |
| 3       | 3          | 102     | 3        |
| 4       | 3          | 102     | 2        |
| 5       | 2          | 103     | 3        |
+---------+------------+---------+----------+
Product table:
+------------+-------+
| product_id | price |
+------------+-------+
| 1          | 10    |
| 2          | 25    |
| 3          | 15    |
+------------+-------+
Output:
+---------+----------+
| user_id | spending |
+---------+----------+
| 101     | 125      |
| 102     | 75       |
| 103     | 75       |
+---------+----------+
Explanation:
User 101 spent 10 * 10 + 1 * 25 = 125.
User 102 spent 3 * 15 + 2 * 15 = 75.
User 103 spent 3 * 25 = 75.
Users 102 and 103 spent the same amount and we break the tie by their ID while user 101 is on the top.
  1. # Write your MySQL query statement below
  2. SELECT s.user_id,
  3.        SUM(s.quantity * p.price) AS spending
  4. FROM Sales s
  5. JOIN Product p
  6.   ON s.product_id = p.product_id
  7. GROUP BY s.user_id
  8. ORDER BY spending DESC, s.user_id ASC;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-22 11:20:10 | 只看该作者
全局:
2339. All the Matches of the League
Easy
Topics
SQL Schema
Pandas Schema
Table: Teams

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| team_name   | varchar |
+-------------+---------+
team_name is the column with unique values of this table.
Each row of this table shows the name of a team.


Write a solution to report all the possible matches of the league. Note that every two teams play two matches with each other, with one team being the home_team once and the other time being the away_team.

Return the result table in any order.

The result format is in the following example.



Example 1:

Input:
Teams table:
+-------------+
| team_name   |
+-------------+
| Leetcode FC |
| Ahly SC     |
| Real Madrid |
+-------------+
Output:
+-------------+-------------+
| home_team   | away_team   |
+-------------+-------------+
| Real Madrid | Leetcode FC |
| Real Madrid | Ahly SC     |
| Leetcode FC | Real Madrid |
| Leetcode FC | Ahly SC     |
| Ahly SC     | Real Madrid |
| Ahly SC     | Leetcode FC |
+-------------+-------------+
Explanation: All the matches of the league are shown in the table.

思路

每两支球队要踢两场,主客场各一次。也就是说,把所有"有序的球队对"列出来,只要两支队不是同一支,每一对就是一场比赛。

自连接 Teams: t1 当主队,t2 当客队。
ON t1.team_name <> t2.team_name: 排除一支球队和自己比赛的情况。
有序对的好处: (A, B) 和 (B, A) 是两条不同的记录,分别代表 A 主场对 B、B 主场对 A,刚好满足"每两队踢两场"。

如果有 n 支球队,结果共有 n × (n − 1) 行。
  1. # Write your MySQL query statement below
  2. SELECT t1.team_name AS home_team,
  3.        t2.team_name AS away_team
  4. FROM Teams t1
  5. JOIN Teams t2
  6.   ON t1.team_name <> t2.team_name;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-22 11:32:03 | 只看该作者
全局:
2346. Compute the Rank as a Percentage
Medium
Topics
SQL Schema
Pandas Schema
Table: Students

+---------------+------+
| Column Name   | Type |
+---------------+------+
| student_id    | int  |
| department_id | int  |
| mark          | int  |
+---------------+------+
student_id contains unique values.
Each row of this table indicates a student's ID, the ID of the department in which the student enrolled, and their mark in the exam.


Write a solution to report the rank of each student in their department as a percentage, where the rank as a percentage is computed using the following formula: (student_rank_in_the_department - 1) * 100 / (the_number_of_students_in_the_department - 1). The percentage should be rounded to 2 decimal places. student_rank_in_the_department is determined by descending mark, such that the student with the highest mark is rank 1. If two students get the same mark, they also get the same rank.

Return the result table in any order.

The result format is in the following example.



Example 1:

Input:
Students table:
+------------+---------------+------+
| student_id | department_id | mark |
+------------+---------------+------+
| 2          | 2             | 650  |
| 8          | 2             | 650  |
| 7          | 1             | 920  |
| 1          | 1             | 610  |
| 3          | 1             | 530  |
+------------+---------------+------+
Output:
+------------+---------------+------------+
| student_id | department_id | percentage |
+------------+---------------+------------+
| 7          | 1             | 0.0        |
| 1          | 1             | 50.0       |
| 3          | 1             | 100.0      |
| 2          | 2             | 0.0        |
| 8          | 2             | 0.0        |
+------------+---------------+------------+
Explanation:
For Department 1:
- Student 7: percentage = (1 - 1) * 100 / (3 - 1) = 0.0
- Student 1: percentage = (2 - 1) * 100 / (3 - 1) = 50.0
- Student 3: percentage = (3 - 1) * 100 / (3 - 1) = 100.0
For Department 2:
- Student 2: percentage = (1 - 1) * 100 / (2 - 1) = 0.0
- Student 8: percentage = (1 - 1) * 100 / (2 - 1) = 0.0

思路

题目给的公式是 (rank - 1) * 100 / (人数 - 1),这正是 MySQL 窗口函数 PERCENT_RANK() 的定义:

PERCENT_RANK() = (rank - 1) / (分区内行数 - 1)

所以只需要把结果乘以 100 再四舍五入。

PARTITION BY department_id: 每个院系单独计算。
ORDER BY mark DESC: 分数最高的排名为 1,对应百分比 0。
并列处理: PERCENT_RANK() 和 RANK() 一样,分数相同的学生得到相同的值,与题目"分数相同则排名相同"的要求一致。
ROUND(..., 2): 保留两位小数。
单人院系的边界情况

如果某个院系只有 1 个学生,按公式分母是 1 - 1 = 0。PERCENT_RANK() 对这种分区直接返回 0,这也是 LeetCode 期望的结果,所以不需要额外处理。
  1. # Write your MySQL query statement below
  2. SELECT student_id,
  3.        department_id,
  4.        ROUND(
  5.            PERCENT_RANK() OVER (PARTITION BY department_id ORDER BY mark DESC) * 100,
  6.            2
  7.        ) AS percentage
  8. FROM Students;
复制代码
回复

使用道具 举报

🔗
 楼主| Myron2017 2026-11-22 11:32:56 | 只看该作者
全局:
2356. Number of Unique Subjects Taught by Each Teacher
Easy
Topics
conpanies icon
Companies
SQL Schema
Pandas Schema
Table: Teacher

+-------------+------+
| Column Name | Type |
+-------------+------+
| teacher_id  | int  |
| subject_id  | int  |
| dept_id     | int  |
+-------------+------+
(subject_id, dept_id) is the primary key (combinations of columns with unique values) of this table.
Each row in this table indicates that the teacher with teacher_id teaches the subject subject_id in the department dept_id.


Write a solution to calculate the number of unique subjects each teacher teaches in the university.

Return the result table in any order.

The result format is shown in the following example.



Example 1:

Input:
Teacher table:
+------------+------------+---------+
| teacher_id | subject_id | dept_id |
+------------+------------+---------+
| 1          | 2          | 3       |
| 1          | 2          | 4       |
| 1          | 3          | 3       |
| 2          | 1          | 1       |
| 2          | 2          | 1       |
| 2          | 3          | 1       |
| 2          | 4          | 1       |
+------------+------------+---------+
Output:  
+------------+-----+
| teacher_id | cnt |
+------------+-----+
| 1          | 2   |
| 2          | 4   |
+------------+-----+
Explanation:
Teacher 1:
  - They teach subject 2 in departments 3 and 4.
  - They teach subject 3 in department 3.
Teacher 2:
  - They teach subject 1 in department 1.
  - They teach subject 2 in department 1.
  - They teach subject 3 in department 1.
  - They teach subject 4 in department 1.
  1. # Write your MySQL query statement below
  2. SELECT teacher_id,
  3.        COUNT(DISTINCT subject_id) AS cnt
  4. FROM Teacher
  5. GROUP BY teacher_id;
复制代码
回复

使用道具 举报

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

本版积分规则

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