将每组的总和除以总计

Divide the sum of each group by the grand total

我想分别求出A组和B组的总和,分别除以总和

我试过用这个:

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

结果应为:

name qt dv
A 32 0.29
B 78 0.70

您可以将聚合和 window 函数组合在一起:

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

您可以交叉连接另一个汇总所有数量的子查询

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