使用sum和rollup获取列的百分比

db2dz4w8  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(488)

我有一张和下面那张一样的table。。。我需要他们使用下表的查询得到的数据。我需要的是计算公式为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
yx2lnoni

yx2lnoni1#

我们可以使用内联视图来计算总数,并执行联接操作。
像这样:

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 ,由一行和第3\u列组成。
该行与从 t ,所以 col3_tot 在每一行上都可用,我们可以在选择列表的表达式中使用它。
(我省略了 WITH ROLLUP 条款来说明 WITH ROLLUP 与获取总数或计算百分比无关。)

相关问题