Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use the SUM Function in Oracle SQL to produce the below output?

I have an SQL Programming question based on Sum Function.Supposing, I have the following table.

       ID   Values 

        1     20
        1     30
        1     100
        2     10
        2     1
        2     12
        3     45
        3     66

How do I calculate the sum of the values pertaining to an ID and add it to a new column. I also would like to group it by ID. For Example:

           ID  Values  Total_Value

            1    20       150
            1    30       150
            1    100      150
            2    10       23
            2    1        23 
            2    12       23
            3    45       111
            3    66       111

Any suggestions would be appreciated. Thanks !

like image 687
Gautham Honnavara Avatar asked Jan 18 '26 15:01

Gautham Honnavara


2 Answers

this can easily be done using a window function:

select id, 
       value,
       sum(value) over (partition by id) as total_value_for_id
from the_table
order by id;

Use analytic functions. That is what they are there for:

select id, value, sum(value) over (partition by id) as totalvalue
from table t
order by id;
like image 22
Gordon Linoff Avatar answered Jan 20 '26 09:01

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!