返回介绍

solution / 2300-2399 / 2346.Compute the Rank as a Percentage / README_EN

发布于 2024-06-17 01:03:07 字数 3114 浏览 0 评论 0 收藏 0

2346. Compute the Rank as a Percentage

中文文档

Description

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

Solutions

Solution 1

# Write your MySQL query statement below
SELECT
  student_id,
  department_id,
  IFNULL(
    ROUND(
      (
        RANK() OVER (
          PARTITION BY department_id
          ORDER BY mark DESC
        ) - 1
      ) * 100 / (COUNT(1) OVER (PARTITION BY department_id) - 1),
      2
    ),
    0
  ) AS percentage
FROM Students;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文