0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[SQL] LeetCodeの無料問題集を活用して、SQLを使いこなし(3)

Posted at

Q178 Rank Scores

Q178.png

質問

スコアをランク付けするSQLクエリを記述します。 2つのスコアの間に同点がある場合は、両方のランキングが同じである必要があります。 同点の場合、次のランキング番号は次の連続する整数値である必要があることに注意してください。

たとえば、上記のスコアテーブルが与えられた場合、クエリは次のレポートを生成する必要があります(最高スコアの順に並べる)。

Code書き方のHINT

この問題は順位付けの関数についての理解を問われています。
REF:https://johobase.com/sqlserver-rank-denserank-rownumber-ntile/

rank():

順位を付ける関数。
比較対象の値が同じ場合は同じ順位になり、その次は順位を飛ばします。

dense_rank():

順位を付ける関数。
比較対象の値が同じ場合は同じ順位になり、その次は順位を飛ばしません。

row_number():

連番ををつける関数。
比較対象の値が同じ場合であっても同じ順位にはならず、順位をカウントアップします。

イメージ図

Q178image.png

rank関数とdense_rank関数の違いは
同じ順位になった場合、その次は順位を飛ばすかどうかです。

今回は、順位を飛ばさないと要求されているので、dense_rankを使います。

Code

select Score,
dense_rank() over (order by Score desc) as `Rank`
from Scores

Code検証結果

Q178_result.png

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?