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 !
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With