mysql - 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
解决方案
我们可以使用内联视图来计算总数,并进行连接操作。
像这样的东西:
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
与获取总数或计算百分比无关。)
推荐阅读
- flutter - Bloc 测试中 BehaviourSubject 的断言问题
- ios - UICollectionView 中的选择和取消选择问题
- java - 如何为预期的异常测试方法添加多个案例?
- sql - 所有插入查询的单个存储过程
- php - PHP:始终在 EXCEL 中显示小数位,即使是零
- rest - 复合查询
- javascript - 如何检查来自 laravel 控制器的 ajax 响应是否为空?
- gradle - 在 gradle 项目中使用 gitlab CI 无法访问 SonarQube 服务器
- html - 为什么当我将鼠标悬停在下拉按钮上时,它的链接没有出现?
- ruby-on-rails - 是否可以在不传递代码块的情况下使用 ruby vcr gem