SQL query: SUM values โ€‹โ€‹before the current record

Basically, having this table:

12.10 2.35 21.45 35.26 

I want in each record to calculate the sum of all previous records, for example:

 12.10 | 12.10 2.35 | 14.45 21.45 | 35.90 35.26 | 71.16 
+4
source share
2 answers

This is called the running total.

If you have a datetime column, you can use something like this:

 SELECT t1.id, t1.transactiondatetime, amount, ( SELECT SUM(amount) FROM dbo.table1 as t1 WHERE t1.transactiondatetime <= t0.transactiondatetime ) AS balance FROM dbo.table1 AS t0 
+2
source

Assuming you have two columns, a primary key called id and a column called value , you can use this:

 SELECT T1.id, SUM(T2.value) FROM table1 T1 JOIN table1 T2 ON T2.id <= T1.id GROUP BY T1.id 

If you donโ€™t have a unique identifier (why not?), You can use ROW_NUMBER to create it.

+3
source

Source: https://habr.com/ru/post/1308746/


All Articles