我想分别得到A组和B组的和,并将它们除以总和。
我试着使用这个:
select name, sum(qt)
from ntbl
group by name
order_id | 名称 | qt|
---|---|---|
1 | A | 12 |
2 | A | 20 |
3 | B | 33 |
4 | B | 45 |
您可以将聚合函数和窗口函数组合在一起:
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.29B|78|0.71
db<gt;小提琴这里