2

我有

Voters(name,vote, score,time)

其中 name 是主键,并且投票是选民投票给的人的 ID。1人可以多次投票。

我必须找到投票次数最多的人的名字。 {Maximum Count(vote)}不使用 max 命令。

4

3 回答 3

3

如果您可以使用 count(),请尝试按它排序您的结果。在 MySQL 中,您的查询可能看起来像

SELECT name, COUNT(vote) AS total_votes
FROM Voters
GROUP BY name
ORDER BY total_votes DESC
LIMIT 1

这将返回投票最多的人及其投票数。

于 2013-04-09T08:33:07.277 回答
1

您可以使用关系代数中的概念。limit 1当多个用户拥有相同数量的选票时,不会给出好的结果。

在 PostgreSQL 上:

with t as (select name, count(*) c from voters group by name)
SELECT t.* from t
except
SELECT t.* from t JOIN t t2 ON t2.c > t.c

SQL Fiddle 示例

和样本数据来证明这一点:

create table voters (name int,vote int);

insert into voters values (1,1);
insert into voters values (1,1);
insert into voters values (1,1);
insert into voters values (1,1);
insert into voters values (1,1);
insert into voters values (1,1);
insert into voters values (1,1);
insert into voters values (1,1);
insert into voters values (2,1);
insert into voters values (2,1);
insert into voters values (2,1);
insert into voters values (2,1);
insert into voters values (2,1);
insert into voters values (2,1);
insert into voters values (2,1);
insert into voters values (2,1);
insert into voters values (2,1);
insert into voters values (3,1);
insert into voters values (3,1);
insert into voters values (3,1);
insert into voters values (3,1);
insert into voters values (3,1);
insert into voters values (3,1);
insert into voters values (3,1);
insert into voters values (3,1);
insert into voters values (3,1);
insert into voters values (4,1);
insert into voters values (4,1);
insert into voters values (4,1);
insert into voters values (4,1);
insert into voters values (4,1);
insert into voters values (5,1);
insert into voters values (5,1);
insert into voters values (5,1);
insert into voters values (5,1);

My solution is based on answer to this question: How can I find MAX with relational algebra?

There is also good explanation of this concept in another answer here Aggregate Relational Algebra (Maximum)

于 2013-04-09T08:46:50.713 回答
0

尝试关注

select count(*) from table where vote=(select max(count(*)) from table) group by vote

希望这对您有所帮助。

于 2013-04-09T08:32:01.783 回答