首页 > 解决方案 > mysql - 使用 sum 和 rollup 获取列的百分比

问题描述

我有一张像下面这样的表格......我需要他们使用表格下方的查询的数据。我需要计算公式为 sum(column3) / total(column3) *100 或 ((0.3333/0.9999)*100) 的百分比。我已经搜索过,但我没有找到任何可以使用 mysql 来完成的事情。甚至有可能吗?谁能给我一些提示?

+----------+---------+----------+--------+
| column1  | column2 | column3 | percentage |
+----------+---------+---------+------------+
| negative |     1   |  0.3333 |     %      |
| neutral  |     1   |  0.3333 |     %      |
| positive |     1   |  0.3333 |     %      |
+----------+---------+----------+-----------+
| Total    |     3   |  0.9999 |     %      |
+----------+---------+----------+-----------+


SELECT 
    column1_text, 
    sum(column2_number) as 'column2', 
    sum(column3_number) as 'column3', 
    percentage_here as 'percentage' 
FROM table 
GROUP BY column1 ASC WITH ROLLUP

标签: mysqlsumpercentagerollup

解决方案


我们可以使用内联视图来计算总数,并进行连接操作。

像这样的东西:

SELECT t.column1
     , SUM(t.column2_number)  AS `column2`
     , SUM(t.column3_number)  AS `column3`
     , ( 100.0 
       * SUM(t.column3_number)
       / s.col3_tot
       )                      AS `percentage`
  FROM `table` t
 CROSS
  JOIN ( SELECT SUM(q.column3_number) AS col3_tot
           FROM `table` q
       ) s 
 GROUP
    BY t.column1
     , s.col3_tot
 ORDER
    BY t.column1 ASC

MySQL 运行内联视图查询以实现派生表s,由一行组成,总共有 column3_number。

该行连接到从 返回的每一行t,因此该值col3_tot在每一行上都可用,我们可以在 SELECT 列表的表达式中使用它。

(我省略了该WITH ROLLUP子句以明确表示WITH ROLLUP与获取总数或计算百分比无关。)


推荐阅读