我有一个问题,就是我如何才能让学生,他/她在哪个位置竞选,我的查询中累积的最高票数按其组织ID过滤。
这是sqlfiddle链接: http://sqlfiddle.com/#!2/fd3d76/3
这是我到目前为止构建的查询:
Select c.c_id, s.s_fname, count(r.c_id)
from results r, candidates c, student s,positioning p, organization o
where r.c_id = c.c_id
AND c.sid = s.sid
AND c.pos_id = p.pos_id
AND o.org_id = c.org_id
AND o.org_id = 1
GROUP BY c.c_id;
根据我提供的链接提供的输出,我只需要看:
约翰,总统,2 - >因为他是总统职位获得最高票数的人
克里斯,副总统,3
Ciel,秘书,3
感谢那些愿意帮助的人。 。 。还有那些只想查看我的问题的人。的xD
答案 0 :(得分:2)
此查询使用变量按投票计数的降序对每个候选人的位置进行编号(即,对他们的位置投票最多的候选人是#1,第二多数投票#2等)。然后它只保留#1候选人。
select * from (
select *,
@rownum := if(@prevposid = pos_id,@rownum+1,1) rownum,
@prevposid := pos_id
from (
select c.c_id, s.s_fname, count(r.c_id), c.pos_id
from results r, candidates c, student s,positioning p, organization o
where r.c_id = c.c_id
and c.sid = s.sid
and c.pos_id = p.pos_id
and o.org_id = c.org_id
and o.org_id = 1
group by c.c_id
order by p.pos_id, count(*) desc
) t1
) t1 where rownum = 1
答案 1 :(得分:0)
http://sqlfiddle.com/#!2/fd3d76/19
SELECT src.c_id, src.s_fname, c
FROM (
SELECT c.c_id, s.s_fname, count(r.c_id) AS c, p.pos_id
FROM results r, candidates c, student s,positioning p, organization o
WHERE r.c_id = c.c_id
AND c.sid = s.sid
AND c.pos_id = p.pos_id
AND o.org_id = c.org_id
AND o.org_id = 1
GROUP BY c.c_id
) src
GROUP BY src.pos_id;
最后你可以添加:
HAVING MAX(src.c);