Skip to content
Advertisement

Sum whole column plus a single row of another column and display in a third column

here is my problem i do have a query the returns to me this table

select * from basic_table;
|----network----|--- previa ----|--- month---|--- organic_value----|---financial_value-----|
 Rental                  1              1          1000                  1250                 
 Rental                  1              3          3750                  3750
 Service                 2              1           2000                 2200
 Maintance               1              2           350                   500

what i need is to sum all the organic_value where the previa is the same + financial_value of each month

so the final table would be

|----network----|--- previa ----|--- month---|--- organic_value----|---financial_value-----| ---NEW_COLUMN--|
 Rental                  1              1          1000                  1250                 (1k + 3,75+0,35k) = 5100 + 1,25k = 6350
 Rental                  1              3          3750                  3750                 (5100) + 3,75k = 8850
 Service                 2              1           2000                 2200                  2000 + 2200 = 4200
 Maintance               1              2           350                   500                  (5100 + 500) =5600

any tips how to tackle this problem?

Advertisement

Answer

That’s a window sum:

select t.*, 
    financial_value  + sum(organic_value) over(partition by previa) as new_column
from mytable t
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement