针对特定类别的顶级用户

时间:2014-01-18 22:54:58

标签: mysql sql

我想找到特定州的主要贡献者: 下面的候选人已经为该州收集了特别的选票。 找到该州的最佳候选人。

create table uservotes(id int, name varchar(50), vote int,state int);

INSERT INTO uservotes VALUES
(1, 'A', 34,1),
(2, 'B', 80,1),
(3, 'bA', 30,1),
(4, 'C', 8,1),
(5, 'D', 4,1),
(6, 'E', 14,2),
(7, 'F', 304,2),
(8, 'AA', 42,3),
(9, 'Ab', 6,3),
(10, 'Aa', 10,3);

create table states(state_id int, name_state varchar(50));

INSERT INTO states VALUES
(1, 'CA'),
(2, 'AL'),
(3, 'AZ'),

我正在寻找:

代表

CAL
2
1
3
4
5

基于贡献的行列。 我怎么做到的。

我真的很感激任何帮助。

先谢谢。

代码尝试了:

select uv.*, (@rank := @rank + 1) as rank
from uservotes uv,states s cross join
     (select @rank := 0) const  on uv.statesid = s.state_id
where name_state = 'CAL'
order by vote desc;

1 个答案:

答案 0 :(得分:1)

这很容易。您可以使用joingroup_concat()

select name_state, substring_index(group_concat(id order by votes desc), ',', 5)
from uservotes uv join
     states s
     on uv.state = s.state
group by name_state;

group_concat()将首先按最高票数排列所有ID。 substring_index()将提取前五个。

编辑:

要获得排名靠前的用户,只需在上述查询中添加where name_state = 'CA'即可。

将它们放在不同的行中:

select uv.*
from uservotes uv join
     states s
     on uv.state = s.state
where state = 'CA'
order by votes desc
limit 5;