LeetCode178: Score ranking

1. Title description

Write a SQL query to achieve score ranking.

If the two scores are the same, the two scores rank (Rank) the same. Please note that the next ranking after the split should be the next consecutive integer value. In other words, there should be no "gap" between the rankings.

+----+-------+
| Id | Score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+

For example, given the above Scorestable, the query should return you (by score from highest to lowest):

+-------+------+
| Score | Rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+

**Important: **For MySQL solutions, if you want to escape the reserved words used as column names, you can use apostrophes before and after the keyword. E.gRank

Two, problem-solving ideas

Method 1: It is best to use SQL's window function dense_rank() for this question, which can achieve the purpose of ranking the effect of the question

Method Two:

  1. Name the two identical scores a and b respectively.
  2. The score in a is compared with the score in b to get the number of unequal b.scores greater than or equal to it under the premise of outputting a.score. Use count(distinct b.score) to remove the duplicates to get the result.
  3. group by a.id otherwise there will only be one piece of data
  4. Finally sort desc according to a.score

In MySql, if you want to escape the reserved words used as column names, you can use apostrophes before and after the keyword. Otherwise there may be an error: You have an error in your SQL syntax……;

Three, my code

# Write your MySQL query statement below
SELECT Score,
    dense_rank() over(order by Score DESC) as 'Rank'
FROM Scores;

Insert picture description here

# Write your MySQL quaery statement below
select a.score as Score, count(adibstinct b.score) as  `Rank`
from scores as a,sacores as b
where a.score<=b.score
group by a.id
order by a.score desc;

Insert picture description here

Four, related knowledge

Regarding the window function, please move to: MySql8.0 window function

GROUP BY statement

The GROUP BY statement is used in combination with the aggregate function to group the result set according to one or more columns.

grammar

SELECT column_name, aggregate_function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name

Example: For a table works
Insert picture description here

We press C to group and view Salary,

//查询不同C的Salary之和
SELECT
	C,
	sum(Salary)
FROM
	works 
GROUP BY
	C

Insert picture description here

After group by grouping and summarizing, the number of rows in the table is changed, and there is only one category in a row.

Guess you like

Origin blog.csdn.net/weixin_45341339/article/details/111387820