Home > front end >  sum() query in sql
sum() query in sql

Time:11-01

I want to show up the result of the equation in sql :

A : 
0.5
0.25
1
1
1

I need to take a current row and divide it by the sum of rows, For ex: 0.5/3.75

I tried this but shows me an error :

select A / sum(A) 
from table X

CodePudding user response:

The way you've used SUM is as an aggregate function. You can't blend row-level and aggregate values in one line.

In most databases, SUM can also be turned into a windowing function with the OVER clause, which I think will do what you want. Try this:

select A / sum(A) OVER () AS ratioValue
from tableX

CodePudding user response:

Just window that SUM():

select a / sum(a) over() as ratio from mytable

Expression sum(a) over() computes the sum of a over the whole table, and makes it available in each and every row.

On the other hand, sum(a) (without the order by) is an aggregate function, that can only be used in the context of group by (either explicit or implicit). Typically, this query gives you the total sum:

select sum(a) as sum_a from mytable

If we were to use this and not use window functions, we would re-phrase your original query like so:

select a / (select sum(a) from mytable) as ratio from mytable

But of course it is much simpler and more efficient to use the window sum here.

  • Related