【问题标题】:how to calulate percentage of the result columns in my mysql database如何计算我的mysql数据库中结果列的百分比
【发布时间】:2015-02-05 10:31:51
【问题描述】:

我在下面有一个表格,记录了用户对几个不同投票的响应;结果存储在响应列

CREATE TABLE IF NOT EXISTS `results` (
  `poll_id` int(11) NOT NULL,
  `response` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  `ip_number` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
  KEY `poll_result` (`poll_id`,`poll_answer`)
) 

每个民意调查都有一个唯一 ID;例如,要求用户在两辆汽车之间进行选择的民意调查将有 poll_id 为 1,但在 响应列 中将有两个可能的汽车的响应,例如 range 或 ford。

SELECT poll_answer  FROM `results` WHERE poll_id = 1  AND   poll_answer = 'Range'

我现在需要起草一个 SQl 查询来确定以下内容;

  1. 用户总数和百分比,来自民意调查 1,他们选择 Range Rover 作为他们最喜欢的汽车

  2. 投票 1 中选择 ford 的用户总数和百分比。

  3. 回复投票 1 的用户总数**

我知道如何从一列中获取总数,但不知道如何从同一列中获取两个总数(使用两个不同的 where 子句);然后计算百分比。

SELECT Count(responce) FROM `results` WHERE poll_id = 1 AND response = 'range' 

【问题讨论】:

  • 查看 SUM、AVG 和 COUNT 聚合函数。
  • 您需要 1 个查询全部还是需要 3 个不同的查询。
  • 嗨 Ankit。感谢您的回复。我想在 1 个查询中完成所有操作。有可能吗?

标签: mysql sql


【解决方案1】:

您可以只使用一个简单的分组来为您提供所有内容,或者如果您想要的话,可以通过添加您的 where 子句来过滤掉。

Select poll_id, (Select Count(poll_id) from results where poll_id = r.poll_id group by poll_id) Total_in_Poll, response, count(response) Total_responded, (Count(response) / ((Select Count(poll_id) from results where poll_id = r.poll_id group by poll_id) * 1.0)  * 100.00) Percent_responded
FROM results r
GROUP BY poll_id, response
order by poll_id

【讨论】:

  • 嗨,克里斯蒂安。谢谢回答。我在 mysql 中尝试了你的答案,但得到了以下错误报告:#1064 - 你的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以获取正确的语法,以便在第 1 行附近使用 'float) * 100.00) Percent_responded FROM results GROUP BY poll_id, response LIMI'
  • @PaulKendal 你能试试更新的吗?我一直忘记 MySQL 不喜欢转换浮点数
  • 非常感谢到目前为止的帮助。我尝试了你的建议,但它给了我这个百分比的答案:100.000000。这显然是错误的。我在响应列中有 12 个条目,10 个范围和 2 个福特。
  • @PaulKendal 抱歉,我是个 dingbat,再试一次。
  • 嘿克里斯蒂安。杰出的。它在 mysqlAdmin 中工作。快速的问题。当我尝试在我的 php 脚本中提取值时,我收到以下消息:mysql_fetch_assoc() 期望参数 1 是资源,对象给出了我尝试提取它的方式:$row = mysql_fetch_assoc($result)。
【解决方案2】:

您可以通过对条件表达式求和来做到这一点:

SELECT count(case poll_answer when 'Range' then 1 end) total_range,
       count(case poll_answer when 'Range' then 1 end) 
             * 100 / count(*)                          perc_range,
       count(case poll_answer when 'Ford' then 1 end)  total_ford,
       count(case poll_answer when 'Ford' then 1 end) 
             * 100 / count(*)                          perc_ford,
       count(*)                                        total_response              
FROM `results` 
WHERE poll_id = 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    • 2021-03-18
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多