関連/類似の質問:MySQL-選択時に行番号を取得します。部分的な結果のみを選択しますが、行の総数を取得します
私は現在このテーブルを持っています:
+----+--------------------+---------------+--------+
| id | accountId | competitionId | rating |
+----+--------------------+---------------+--------+
| 1 | theidoftheaccount1 | 1 | 100 |
| 2 | theidoftheaccount2 | 3 | 90 |
| 3 | theidoftheaccount3 | 1 | 80 |
| 4 | theidoftheaccount4 | 1 | 50 |
+----+--------------------+---------------+--------+
で行を取得したいaccountId='theidoftheaccount3'
ので、通常のSQLステートメントを呼び出しますSELECT * FROM competitors WHERE competitionId='someotherid1' AND accountId='theidoftheaccount3 ' ORDER BY rating DESC
。すべて問題ありません。
問題:取得した行の行番号を知りたいのですが、を持っている他のすべての行からのみcompetitionId='someotherid1'
です。この行番号は、同じ競技会の他のすべての競技者の中での競技者の「ランク」になります。
だから基本的に一日の終わりに私は戻ってきます:
+----+--------------------+---------------+--------+-----------+
| id | accountId | competitionId | rating | rowNumber |
+----+--------------------+---------------+--------+-----------+
| 3 | theidoftheaccount3 | 1 | 80 | 2 |
+----+--------------------+---------------+--------+-----------+
これはどのように行うことができますか?
1つの方法はrow_number()
、サブクエリで使用することです。
select c.*
from (select c.*,
rank() over (partition by competitionid order by rating desc) as ranking
from competitors c
where competitionId = 'someotherid1'
) c
where accountId = 'theidoftheaccount3';
編集:
ウィンドウ関数のない代替手段は次のとおりです。
select count(*) + 1 as ranking
from competitors c
where c.competitionId = 'someotherid1' and
c.rating > (select c2.rating
from competitors c2
where c2.competitionid = c.competitionId and
c2.accountId = 'theidoftheaccount3'
);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加