代码之家  ›  专栏  ›  技术社区  ›  jame

获取平均百分比

  •  1
  • jame  · 技术社区  · 16 年前

    我不确定该怎么做,要么是因为太晚了,要么我是mysql的noob(老实说,可能两者都是)。

    我有一个名为“投票”的表格,包括:

    ID, poll_id, answer_id, ip, time_posted
    

    我需要做的是,对于特定投票ID中的每个唯一答案ID,计算出该答案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 (%)
    

    显然,所有的百分比加起来应该等于100。还要注意的是,返回的每个百分比的字段名不一定按任何顺序排列。

    我的意思是,即使查询只返回每个答案的总投票数和投票数,我也可以用php轻松计算。

    有人能给我指点一下吗?

    编辑:这是我目前所拥有的,但不起作用:

    SELECT (SELECT COUNT(*) FROM poll_votes) AS total, answer_id, COUNT(answer_id) / total * 100 AS percentage GROUP BY answer_id
    
    3 回复  |  直到 11 年前
        1
  •  1
  •   Richard    16 年前

    简单的解决办法是

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

    使用

    select count(ID) from poll_votes
    

    预先获取总行数

        2
  •  0
  •   Mercer Traieste    16 年前

    由于内部选择,不是一个漂亮的答案,但应该有效(答案字段使用文本而不是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
    
        3
  •  0
  •   Alexey Sviridov    16 年前

    当然,你不能到处使用字段别名作为字段值(我是关于你的‘全部’asias’)。即使在“组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秒的列来获得“纯”。