/ /集計(カウント)によるクエリ結果のランク付け-mysql、join、aggregate-functions

クエリ結果の集計(count)によるランキング - mysql、join、aggregate-functions

集計関数でランク付けされた値を取得しようとしていますが、(ORMがクエリを呼び出すのではなく)MySQLクエリ内で実行できるかどうかを確認したいと思います。

私が持っているテーブルとデータは次のようなものです。

CREATE TABLE `interactions` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`account` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;

INSERT INTO `interactions` VALUES
(1, "xyz", "2017-01-01 00:05:01"),
(2, "xyz", "2017-01-01 00:05:10"),
(3, "abc", "2017-01-01 00:05:21"),
(4, "xyz", "2017-01-01 00:05:43"),
(5, "def", "2017-01-01 00:05:47"),
(6, "xyz", "2017-01-01 00:05:49"),
(7, "abc", "2017-01-01 00:05:50"),
(8, "abc", "2017-01-01 00:05:59");

これまで私は持っている:

set @curRank := 0;

select
@curRank := @curRank + 1 AS rank,
der.account,
der.searches
from
interactions
right join
(select account, count(id) AS searches from interactions group by account order by searches) AS der
on
der.account = interactions.account;

しかし、これはすべてのアカウントを出力します(正しい searches 値-ただし、複数回ランク付けされています):

 1    abc        3
2    abc        3
3    abc        3
4    def        1
5    xyz        4
6    xyz        4
7    xyz        4
8    xyz        4

を探しています:

 1    abc        3
2    def        1
3    xyz        4

私は共同ランクを気にしないことを言及する必要があります-2つのアカウントがテーブルで同じカウントになる場合、それらが次々にランク付けされるかどうか(またはどの順序でランク付けされるか)は関係ありません。

回答:

回答№1は0

SELECTにDISTINCTを追加すると、クエリが修正されます。

set @curRank := 0;

select distinct
der.account,
der.searches,
@curRank := @curRank + 1 AS rank
from
interactions
right join
(select account, count(id) AS searches from interactions group by account order by searches) AS der
on
der.account = interactions.account;