Consecutive sum of a column in SQL

Asked

Viewed 320 times

1

I wanted to calculate the data from a bad table as follows

I have a price column

100 140 300 200

wanted to generate a second column that would make a consecutive sum of the previous table

100 240 540 740

inserir a descrição da imagem aqui

I managed to do with Python a logic but I don’t know how to do in SQL

  • you want to add a column with sum to an existing table, or you want to create a table with a column that repeats the first record, if there is no and sum with previous if already exists?

1 answer

1


To do this, use the OVER about the function SUM. The OVER will make the SUM apply under one condition, in which case it will be all numbers up to the current "offset".

SELECT preço, SUM(preço) OVER (ORDER BY preço) AS "SOMA CONSECUTIVA" FROM valores;

See working on SQL Fiddle.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.