2017-02-02 145 views
1

我試圖通過聚合函數獲得排名值 - 我想看看它是否可以在MySQL查詢(而不是ORM調用查詢)內完成。排名查詢結果聚合(計數)

表和數據我已經是這樣的:

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 

我應該提及的是,我不在乎聯合排名 - 如果兩個賬戶在表格中以相同的計數結束,那麼他們是否依次排列(或排列順序)並不重要)。

+0

見http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what -seems-to-a-very-simple-sql-query – Strawberry

+0

@Strawberry - 你能否指出你認爲從這個問題中缺少的東西?只是一個數據集? – HorusKol

+0

鏈接的答案是不言自明的 – Strawberry

回答

0

添加DISTINCT的SELECT修復查詢:

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;