0
0

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.

MySQLで取得結果にランクをつける

Last updated at Posted at 2020-11-17

金額の高い順にランクをつける。

対象のテーブル

select
*
from
products

+-----------+-------+
| name      | price |
+-----------+-------+
| スイカ    |    80 |
| バナナ    |    50 |
| ぶどう    |    50 |
| みかん    |   100 |
| りんご    |    50 |
| レモン    |    30 |
+-----------+-------+

相関サブクエリを用いる方法

SELECT P1.name,
P1.price,
(
    SELECT COUNT(P2.price)
    FROM Products P2
    WHERE P2.price > P1.price
) + 1 AS rank_1
FROM Products P1
ORDER BY
rank_1;

+-----------+-------+--------+
| name      | price | rank_1 |
+-----------+-------+--------+
| みかん    |   100 |      1 |
| スイカ    |    80 |      2 |
| バナナ    |    50 |      3 |
| ぶどう    |    50 |      3 |
| りんご    |    50 |      3 |
| レモン    |    30 |      6 |
+-----------+-------+--------+

ランクを0から始めたい場合、+1を消せば良い。
また、count(distinct p2.price)とすれば、
同じ順位にならず、飛び石でランクがつけられる。

みかんのrank_1の値に1がつく理由としては、
みかんのprice(100)以上のレコードがないため、
where P2.price > P1.priceをcountした結果が0になるため。

また、自己結合を用いる方法もある。

SELECT P1.name,
MAX(P1.price) AS price,
COUNT(P2.name) +1 AS rank_1
FROM Products P1 LEFT OUTER JOIN Products P2
ON P1.price < P2.price
GROUP BY P1.name
ORDER BY
rank_1;

こちらを参考にさせていただきました。
達人に学ぶSQL徹底指南書 第2版 初級者で終わりたくないあなたへ

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?