所以我以这种格式将数据放在表格中
Candidate Name Position ID Total Votes
_____________ _____________ _____________
Name 1 1 1
Name 2 1 3
Name 3 2 1
Name 4 2 4
Name 5 3 1
Name 6 3 5
我如何获得每个位置的每位获胜者。我尝试了很多查询,但没有得到正确的结果。任何帮助将不胜感激。
答案 0 :(得分:0)
让您的表格由t
表示。请注意,此查询确实为所有获胜者提供了最大票数。
with position_max(position, max_vote) as
(
select position, max(votes)
from t
group by position
)
select t.name, t.position
from t, position_max
where t.position=position_max.position and t.votes=position_max.max_vote;
没有with
- 子句:
select t.name, t.position
from t
join (
select position, max(votes) as votes
from t
group by position
) ta on ta.position=t.position
where t.votes=ta.votes;
答案 1 :(得分:0)
这是一个可能有点天真的解决方案,但我似乎无法想到更好的版本。
让我们考虑一个表格,详情如下:
CREATE TABLE VOTING (Name TEXT, position integer, votes integer);
INSERT INTO VOTING VALUES("Name 1", 1, 1);
INSERT INTO VOTING VALUES("Name 2", 1, 3);
INSERT INTO VOTING VALUES("Name 3", 2, 1);
INSERT INTO VOTING VALUES("Name 4", 2, 4);
INSERT INTO VOTING VALUES("Name 5", 3, 1);
INSERT INTO VOTING VALUES("Name 6", 3, 5);
查询是:
SELECT name,
A.position,
votes
FROM voting A,
(SELECT position,
Max(votes) AS M
FROM voting
WHERE position IN (SELECT DISTINCT( position )
FROM voting)
GROUP BY position) B
WHERE A.position = B.position
AND A.votes = B.m;
我的思考过程如下:
position
值。position
检索该位置的max(votes)
。max(votes)
列附加到position
值匹配的原始表格中,这样就意味着每个行和位置对都有可用的该位置的最大值(投票数)。(ASC/DESC)
结果如下:
Name position votes
------ -------- -----
Name 2 1 3
Name 4 2 4
Name 6 3 5
以下是正在运行的示例的链接:http://sqlfiddle.com/#!9/8d7ce6/54/0