简体   繁体   中英

Divide the sum of each group by the grand total

I want to get the sum of group A and B separately, and divide each by the total sum.

I tried to use this:

select name, sum(qt)
from ntbl
group by name 
order_id name qt
1 A 12
2 A 20
3 B 33
4 B 45

Result should be as:

name qt dv
A 32 0.29
B 78 0.70

You can combine aggregate and window functions together:

select name
     , sum(qt) as sum_qt
     , sum(qt) / sum(sum(qt)) over () * 100 as pct_qt
from t
group by name

You can crossjoin another subquery that sums up all quantities

CREATE TABLE ntbl ( `order_id` INTEGER, `name` VARCHAR(1), `qt` INTEGER ); INSERT INTO ntbl (`order_id`, `name`, `qt`) VALUES ('1', 'A', '12'), ('2', 'A', '20'), ('3', 'B', '33'), ('4', 'B', '45');
 SELECT name, sum_name, ROUND(sum_name/sum_qt,2) as dv FROM (select name,SUM(qt) sum_name from ntbl group by name) q1 CROSS JOIN (SELECT SUM(`qt`) sum_qt FROM ntbl) q2
 name | sum_name | dv:--- | -------: |  ---: A |  32 |  0.29 B |  78 |  0.71 

db<>fiddle here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM