Home > Back-end >  Divide the sum of each group by the grand total
Divide the sum of each group by the grand total

Time:03-16

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

CodePudding user response:

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

CodePudding user response:

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

  • Related