【问题标题】:mysql - get the percentage of a column using sum and rollupmysql - 使用 sum 和 rollup 获取列的百分比
【发布时间】:2018-05-15 15:28:22
【问题描述】:

我有一张像下面这样的表格...我需要他们使用表格下方的查询的数据。我需要计算公式为 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

【问题讨论】:

标签: mysql sum percentage rollup


【解决方案1】:

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

类似这样的:

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 与获取总数或计算百分比无关。)

【讨论】:

  • 您应该在GROUP BY 子句中添加col3_tot 以避免在严格模式下出错。
  • @PaulSpiegel:好点。是的,SELECT 列表中的非聚合表达式应该出现在 GROUP BY 子句中(或者在功能上依赖于 GROUP BY 子句中的表达式)。我们通过在sql_mode 中包含ONLY_FULL_GROUP_BY 来让MySQL 像其他RDBMS 一样运行并抛出错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-02
  • 2022-11-23
  • 1970-01-01
  • 2021-11-25
相关资源
最近更新 更多