leetcode-Database-178. Score ranking-mysql solution and use dense_rank ()

Original title: https://leetcode-cn.com/problems/rank-scores/

      The problem-solving directory
      writes a SQL query to achieve score ranking. If the two scores are the same, the two ranks are the same. Please note that the next place after the split should be the next consecutive integer value. In other words, there should be no "spacing" between rankings.

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

      For example, based on the Scores table given above, your query should return (in order of highest to lowest score):

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

1. The first solution

      This question is very simple if you know dense_rank (); if you don't know it, it's a little difficult. (mySql does not have dense_rank (), oracle and hive do)

select
    score as Score,
    dense_rank() over(order by score desc) as Rank
from scores;

      Let's vomit, I don't know why, there is a problem with the alias:
There is a problem with the alias

2. The second solution

      Then talk about how mysql solves the problem, that is, the method without dense_rank ():

select
	s1.score Score,
	(select 
		count(distinct(s2.score))
	from scores s2 
	where s2.score >= s1.score 
	) as Rank  
from scores s1
order by Rank

      This is quite interesting.
      
      

Published 48 original articles · Like 36 · Visits 130,000+

Guess you like

Origin blog.csdn.net/weixin_42845682/article/details/105252542