LoginSignup
17
20

More than 5 years have passed since last update.

MySQLでランキングを取得する際のwhereにcaseを用いてみた。

Posted at

備忘録。
case文便利っす。

http://ameblo.jp/wataru420/entry-11132562539.html
ここを見て、whereにも使えるのではないかと思いやってみた。

こんなテーブルに、

CREATE TABLE `user_score` (
  `userId` int(10) unsigned NOT NULL COMMENT 'ユーザーID',
  `pointTotal` bigint(20) unsigned NOT NULL COMMENT '累計獲得pt',
  `winCountTotal` int(10) unsigned NOT NULL COMMENT '累計勝利数',
  PRIMARY KEY (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

こんなデータを入れて、

insert into user_score (userId, pointTotal, winCountTotal) values
(118, 0, 22),
(342, 90795, 20),
(576, 25125, 19),
(386, 4200, 10),
(335, 200, 1),
(80, 200, 1),
(512, 190, 1),
(28, 236, 1),
(39, 250, 0);

で、

  1. winCoutTotalで比較
  2. winCountTotalが同じならpointTotalで比較
  3. pointTotalも同じなら同順位

といった感じの優先順でランク付けしたいので、
こんな風に実行すると、

select userId,pointTotal, winCountTotal,
(select count(userId)+1
    from user_score b
    where case 
        when b.winCountTotal = a.winCountTotal then b.pointTotal > a.pointTotal else b.winCountTotal > a.winCountTotal end
) as rank
from user_score a
order by rank,pointTotal desc, userId;

こんな感じで取得できた。

userId pointTotal winCountTotal rank
118 0 22 1
342 90795 20 2
576 25125 19 3
386 4200 10 4
28 236 1 5
335 200 1 6
80 200 1 6
512 190 1 8
39 250 0 9
17
20
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
17
20