search

Home  >  Q&A  >  body text

新标题:Calculate the average of each group relative to the total sum

I want to get the sum of group A and group B respectively, and then divide by the sum.

I tried using this:

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

The result should be:

Name qt dv
one 32 0.29
B 78 0.70


P粉852578075P粉852578075340 days ago358

reply all(2)I'll reply

  • P粉561438407

    P粉5614384072023-12-29 13:20:15

    You can cross-join another subquery that sums all quantities

    db<>violinhere

    reply
    0
  • P粉005417748

    P粉0054177482023-12-29 09:01:28

    You can combine aggregate functions 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

    reply
    0
  • Cancelreply