【问题标题】:How to calculate percentage for number of values in a column in sql?如何计算sql中列中值数量的百分比?
【发布时间】:2016-09-25 00:19:30
【问题描述】:

我有一个名为 text 的列和另一个名为“categories”的列,其中包含三个值“positive”、“negative”、“neutral”。

如何计算类别中每个文本值的百分比? 例如,如果我有 3 行,1 行是正数,1 行是负数,1 行是中性的,什么查询会产生 33% 正数、33% 负数和 33% 中性?

这是我要到的阶段......

SELECT COUNT(category), category  FROM tweets GROUP BY category

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    一种方法

    select category, count, count/total percent
      from 
      (
        select category, count(category) count
          from tweets 
         group by category
      ) c JOIN (
        select count(*) total
          from tweets
      ) t
    

    输出:

    +---------+--------+---------+ |类别 |计数 |百分比 | +---------+--------+---------+ |负| 1 | 0.3333 | |中性 | 1 | 0.3333 | |积极| 1 | 0.3333 | +---------+--------+---------+

    ...是否有可能只返回 33% 而不是 0.3333?

    select category, count, round(count / total * 100) percent
      from 
      (
        select category, count(category) count
          from tweets 
         group by category
      ) c JOIN (
        select count(*) total
          from tweets
      ) t
    
    +---------+--------+---------+ |类别 |计数 |百分比 | +---------+--------+---------+ |负| 1 | 33 | |中性 | 1 | 33 | |积极| 1 | 33 | +---------+--------+---------+

    如果您想添加 %,您可以使用 do concat(round(count / total * 100), '%'),但我强烈建议您在客户端代码中添加(任何格式)。

    【讨论】:

    • 感谢@peterm 的回答是否有可能只返回 33% 而不是 0.3333?
    【解决方案2】:

    作为说明,我认为这更简单地使用单个子查询编写:

    select t.category, count(*) / t.total,       -- number
           concat(100 * count(*) / t.total, '%') -- string
    from tweets t join
         (select count(*) as total) t
    group by category;
    

    如果你知道只有三个类别,我会把它们放在一行中:

    select avg(category = 'positive') as p_positive,
           avg(category = 'negative') as p_negative
           avg(category = 'neutral') as p_neutral
    from tweets t;
    

    此查询使用 MySQL 的特性,即布尔表达式在数字上下文中被视为整数,“1”表示真,“0”表示假。

    【讨论】:

      【解决方案3】:

      只需对您当前的查询进行小修改:

      SELECT COUNT(category)/COUNT(*), category FROM tweets GROUP BY category
      

      【讨论】:

      • COUNT(category)/COUNT(*) 将始终返回 1 假设 category 不包含空值
      猜你喜欢
      • 1970-01-01
      • 2021-11-22
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      • 2023-02-01
      • 2010-10-13
      • 2013-05-23
      相关资源
      最近更新 更多