获得平均百分比

时间:2009-09-03 08:57:29

标签: mysql sql select

我不确定如何解决这个问题,因为它迟到了,或者我是一个MySQL菜鸟(可能都是诚实的)。

我有一个名为'poll_votes'的表,其中包含:

ID, poll_id, answer_id, ip, time_posted

我需要做的是,针对特定poll_id中的每个唯一answer_id,计算answer_id所依据的答案总数中的百分比。我不是很擅长措辞我需要做什么,所以这里是查询应返回的内容(单行):

total -> total number of answers for this poll_id
[0] -> the percentage of 'total' that this makes up eg. 32 (%)
[1] -> the percentage of 'total' that this makes up eg. 16 (%)
[2] -> the percentage of 'total' that this makes up eg. 52 (%)

显然,加在一起的所有百分比应该等于一百。另请注意,返回的每个百分比的字段名称不一定是任何顺序。

我的意思是即使查询只返回了每个answer_id的总票数和投票数,我也可以在PHP中轻松计算出来。

有人可以给我任何指示吗?

编辑:这是我到目前为止所做的,但它不起作用:

SELECT (SELECT COUNT(*) FROM poll_votes) AS total, answer_id, COUNT(answer_id) / total * 100 AS percentage GROUP BY answer_id

3 个答案:

答案 0 :(得分:1)

简单的解决方案是

select answer_id, count(answer_id) as answercount
from poll_votes
group by answer_id

并使用

select count(ID) from poll_votes

预先获得总行数

答案 1 :(得分:0)

由于内部选择不是一个美丽的答案,但应该有效(使用文本代替int作为答案字段):

drop table if exists ANSWERS;

create table ANSWERS (
  ID int not null auto_increment,
  ANSWER text,
  primary key (ID)
);

insert into ANSWERS (ANSWER) values ("Alpha");
insert into ANSWERS (ANSWER) values ("Beta");
insert into ANSWERS (ANSWER) values ("Gamma");
insert into ANSWERS (ANSWER) values ("Gamma");
insert into ANSWERS (ANSWER) values ("Delta");
insert into ANSWERS (ANSWER) values ("Delta");
insert into ANSWERS (ANSWER) values ("Delta");

select 
    ANSWER,
    count(ANSWER) / (select count(*) from ANSWERS) * 100 AS PERCENTAGE
from ANSWERS
group by ANSWER
order by PERCENTAGE;

试驾:

mysql -u root test < percentage-usage.sql
ANSWER  PERCENTAGE
Alpha   14.2857
Beta    14.2857
Gamma   28.5714
Delta   42.8571

答案 2 :(得分:0)

当然你不能在任何地方使用字段别名作为字段值(我是关于你的'总'aslias)。即使在“group by”子句

中也不能使用别名

所以你必须使用像这样的

select answer_id, count(*) / (select count(*) from poll_votes where poll_id = pv.poll_id)
from poll_votes pv
where pv.poll_id = _your_specific_poll_id_
group by answer_id

你可以乘以100秒的列来获得“纯粹”的持续性。