在案例声明中汇总数据

问题描述 投票:-1回答:1

我想创建4个组,基于 提交量 然后计算每组占总人数的百分比。提交量

到目前为止,我使用了这个查询

SELECT CASE
           WHEN submit_volume <= 60 then '60 Request'
           WHEN submit_volume > 60
                AND submit_volume <= 150 then '60-150 Request'
           WHEN submit_volume > 150
                AND submit_volume <= 1000 then '150-1K Request'
           WHEN submit_volume > 1000 then 'Over 1K Request'
       END,
       sum(CASE
               WHEN submit_volume <= 60 then submit_volume
               WHEN submit_volume > 60
                    AND submit_volume <= 150 then submit_volume
               WHEN submit_volume > 150
                    AND submit_volume <= 1000 then submit_volume
               WHEN submit_volume > 1000 then submit_volume
           END)
FROM mydatabase.submit_volume
GROUP BY 1

并得到了这个表

| group| sum| 
| 60-150 Request   | 87247    |
| 60 Request       | 105934   |
| Over 1K Request  | 2385947  |
| 150-1K Request   | 777186   |

那么我可以不使用子查询而得到每组的百分比吗?我试了一下,但所有组的百分比都是100%。

sum(CASE
   WHEN submit_volume <= 60 then submit_volume
   WHEN submit_volume > 60
      AND submit_volume <= 150 then submit_volume
   WHEN submit_volume > 150
      AND submit_volume <= 1000 then submit_volume
   WHEN submit_volume > 1000 then submit_volume
END) / sum(submit_volume) * 100.0 as percentage
mysql case aggregate
1个回答
1
投票

CASE 你用来分组的表达式可以被简化,并且你可以用 SUM() 只需 submit_volume. 交叉连接到表中的一个查询,返回总和。submit_volume 的表,并使用它来获得百分比。

SELECT CASE
           WHEN sv.submit_volume <= 60 then '60 Request'
           WHEN sv.submit_volume <= 150 then '60-150 Request'
           WHEN sv.submit_volume <= 1000 then '150-1K Request'
           WHEN sv.submit_volume > 1000 then 'Over 1K Request' -- or ELSE 'Over 1K Request'
       END request,
       SUM(sv.submit_volume) / MAX(t.total) * 100.0 percentage 
FROM mydatabase.submit_volume sv 
CROSS JOIN (SELECT SUM(submit_volume) total FROM mydatabase.submit_volume) t
GROUP BY request

对于MySql 8.0以上的版本,它更容易与 SUM() 窗口功能。

SELECT CASE
           WHEN submit_volume <= 60 then '60 Request'
           WHEN submit_volume <= 150 then '60-150 Request'
           WHEN submit_volume <= 1000 then '150-1K Request'
           WHEN submit_volume > 1000 then 'Over 1K Request' -- or ELSE 'Over 1K Request'
       END request,
       SUM(submit_volume) / SUM(SUM(submit_volume)) OVER () * 100.0 percentage 
FROM submit_volume 
GROUP BY request

请看一个简化的 演示.

© www.soinside.com 2019 - 2024. All rights reserved.