如何计算投票的正确语法是什么

时间:2017-09-12 09:13:14

标签: c# mysql

这是我们用来计算投票数量的学生的代码。

SELECT candidate,position, COUNT(studentNumber) AS 'Candidate Votes'
FROM dbvotingsystem.votes WHERE organization = 'iSITE' GROUP BY candidate
ORDER BY position;

图像是表格中数据的样本。

enter image description here OM / CwvSt.png

2 个答案:

答案 0 :(得分:1)

如果winner是每个组中的最大Candidate Votes,那么Secretary的获胜者应为Many,请检查以下sql:

SELECT
    position,
    substring_index(group_concat(candidate order by `Candidate Votes` desc), ',', 1) winner,
    max(`Candidate Votes`) as `Candidate Votes`
FROM (
    SELECT candidate, position, COUNT(studentNumber) AS 'Candidate Votes'
    FROM dbvotingsystem.votes
    WHERE organization = 'iSITE'
    GROUP BY candidate
) votes
GROUP BY position

结果:

|    position | winner | Candidate Votes |
|-------------|--------|-----------------|
|   President | Audrey |               7 |
|   Secretary |   Many |               8 |
|   Treasurer |  Barry |              10 |
| V.President |   Juan |               9 |
SQLFiddle中的

DEMO

答案 1 :(得分:0)

这是一种使用变量对结果进行排名的方法。请注意,group by使用所有选定列的方式,并且可以照顾绘制。

drop table if exists t;
create table t(id int auto_increment primary key, candidate varchar(1),position varchar(3));

insert into t (candidate,position) values
('a','p'),('b','p'),('a','p'),
('c','vp'),('c','vp'),('d','vp'),('d','vp');

select position,candidate, votes, rn as rank
from
(
select position,candidate, votes,
         if(s.position <> @p,@rn:=1,if(s.votes <> @v,@rn+1,@rn=1)) rn,
         @p:=position p,
         @v:=votes v
from
(
select position,candidate , count(*) as votes 
from t
group by position,candidate 
) s
,(select @rn:=0,@p:='',@v:='') r
order by position,candidate, votes desc
) t
where rn = 1