【问题标题】:MySql Calculate Grouped Fields Percentage and Show on one rowMySql 计算分组字段百分比并显示在一行
【发布时间】:2021-01-04 13:20:20
【问题描述】:
+--------+--------+--------+------------+
| line | field1 | count|
| x |    a | 2 |
| x |    b | 2 |
| x |    c | 1 |
| y |    a | 1 |
| y |    b | 1 |
| y |    c | 1 |
| y |    d|  1 |

如您所见,上表表示的行是分组字段,我尝试获取类似或类似的查询结果:

+--------+--------+--------+------------+
| line | field1-percentage|
| x |  a-%40,b-%40,c-%20 |
| y |  a-%25,b-%25,c-%20 |

【问题讨论】:

标签: mysql sql group-by percentage


【解决方案1】:

列名已更改(countReserved word)。

对于 MySQL 8+ 使用

WITH cte AS ( SELECT category, entity, SUM(amount) amount
              FROM test
              GROUP BY category, entity WITH ROLLUP )
SELECT category, GROUP_CONCAT(t1.entity, '-%', ROUND(100 * t1.amount / t2.amount)) percentage
FROM cte t1
JOIN cte t2 USING (category)
WHERE t2.entity IS NULL
GROUP BY category;

对于 MySQL 5.x 使用:

SELECT category, GROUP_CONCAT(t1.entity, '-%', ROUND(100 * t1.amount / t2.amount)) percentage
FROM ( SELECT category, entity, SUM(amount) amount
       FROM test
       GROUP BY category, entity ) t1
JOIN ( SELECT category, SUM(amount) amount
       FROM test
       GROUP BY category ) t2 USING (category)
GROUP BY category;

fiddle

【讨论】:

  • 真的非常感谢
猜你喜欢
  • 1970-01-01
  • 2012-09-08
  • 2013-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-05
相关资源
最近更新 更多