3

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

2 Answers 2

5

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
3
  • so if i want to multiply the ration_qt by 100 how to do so i did like this but didnt work `` sum(qt) / sum(sum(qt)) * 100 over () as ratio_qt``
    – rh2o
    Mar 15, 2022 at 20:34
  • you can't, you need another outer query, one perk of window functions
    – nbk
    Mar 15, 2022 at 20:49
  • 1
    See revised answer. The "over" is part of divisor.
    – Salman A
    Mar 15, 2022 at 21:03
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.